Beispiel #1
0
		protected DirectResponse(OpenIdRelyingParty relyingParty, ServiceEndpoint provider, IDictionary<string, string> args) {
			if (relyingParty == null) throw new ArgumentNullException("relyingParty");
			if (provider == null) throw new ArgumentNullException("provider");
			if (args == null) throw new ArgumentNullException("args");
			RelyingParty = relyingParty;
			Provider = provider;
			Args = args;

			// Make sure that the OP fulfills the required OpenID version.
			// We don't use Provider.Protocol here because that's just a cache of
			// what we _thought_ the OP would support, and our purpose is to double-check this.
			ProtocolVersion detectedProtocol = Protocol.DetectFromDirectResponse(args).ProtocolVersion;
			if (detectedProtocol < relyingParty.Settings.MinimumRequiredOpenIdVersion) {
				throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
					Strings.MinimumOPVersionRequirementNotMet,
					Protocol.Lookup(relyingParty.Settings.MinimumRequiredOpenIdVersion).Version,
					Protocol.Lookup(detectedProtocol).Version));
			}

			if (Logger.IsErrorEnabled) {
				if (provider.Protocol.QueryDeclaredNamespaceVersion != null) {
					if (!Args.ContainsKey(Protocol.openidnp.ns)) {
						Logger.ErrorFormat("Direct response from provider lacked the {0} key.", Protocol.openid.ns);
					} else if (Args[Protocol.openidnp.ns] != Protocol.QueryDeclaredNamespaceVersion) {
						Logger.ErrorFormat("Direct response from provider for key {0} was '{1}' rather than '{2}'.",
							Protocol.openid.ns, Args[Protocol.openidnp.ns], Protocol.QueryDeclaredNamespaceVersion);
					}
				}
			}
		}
 public IDictionary<string, string> SendDirectMessageAndGetResponse(ServiceEndpoint provider, IDictionary<string, string> fields)
 {
     OnSending(provider, fields);
     var results = channel.SendDirectMessageAndGetResponse(provider, fields);
     OnReceiving(provider, results);
     return results;
 }
 protected virtual void OnReceiving(ServiceEndpoint provider, IDictionary<string, string> fields)
 {
     var receiving = Receiving;
     if (receiving != null) {
         receiving(provider, fields);
     }
 }
Beispiel #4
0
        public string GetBuildDirectoryHashKey(IExecutionContext executionContext, ServiceEndpoint endpoint)
        {
            // Validate parameters.
            Trace.Entering();
            ArgUtil.NotNull(executionContext, nameof(executionContext));
            ArgUtil.NotNull(executionContext.Variables, nameof(executionContext.Variables));
            ArgUtil.NotNull(endpoint, nameof(endpoint));
            ArgUtil.NotNull(endpoint.Url, nameof(endpoint.Url));

            // Calculate the hash key.
            const string Format = "{{{{ \r\n    \"system\" : \"build\", \r\n    \"collectionId\" = \"{0}\", \r\n    \"definitionId\" = \"{1}\", \r\n    \"repositoryUrl\" = \"{2}\", \r\n    \"sourceFolder\" = \"{{0}}\",\r\n    \"hashKey\" = \"{{1}}\"\r\n}}}}";
            string hashInput = string.Format(
                CultureInfo.InvariantCulture,
                Format,
                executionContext.Variables.System_CollectionId,
                executionContext.Variables.System_DefinitionId,
                endpoint.Url.AbsoluteUri);
            using (SHA1 sha1Hash = SHA1.Create())
            {
                byte[] data = sha1Hash.ComputeHash(Encoding.UTF8.GetBytes(hashInput));
                StringBuilder hexString = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                {
                    hexString.Append(data[i].ToString("x2"));
                }

                return hexString.ToString();
            }
        }
        public void ReturnsCorrectHashKey()
        {
            using (TestHostContext tc = new TestHostContext(this))
            {
                // Arrange.
                var executionContext = new Mock<IExecutionContext>();
                List<string> warnings;
                executionContext
                    .Setup(x => x.Variables)
                    .Returns(new Variables(tc, copy: new Dictionary<string, string>(), maskHints: new List<MaskHint>(), warnings: out warnings));
                executionContext.Object.Variables.Set(Constants.Variables.System.CollectionId, "7aee6dde-6381-4098-93e7-50a8264cf066");
                executionContext.Object.Variables.Set(Constants.Variables.System.DefinitionId, "7");
                var endpoint = new ServiceEndpoint
                {
                    Url = new Uri("http://contoso:8080/tfs/DefaultCollection/gitTest/_git/gitTest"),
                };
                var sourceProvider = new ConcreteSourceProvider();
                sourceProvider.Initialize(tc);

                // Act.
                string hashKey = sourceProvider.GetBuildDirectoryHashKey(executionContext.Object, endpoint);

                // Assert.
                Assert.Equal("5c5c3d7ac33cca6604736eb3af977f23f1cf1146", hashKey);
            }
        }
Beispiel #6
0
        public static CheckAuthRequest Create(OpenIdRelyingParty relyingParty, ServiceEndpoint provider, IDictionary<string, string> query)
        {
            if (relyingParty == null) throw new ArgumentNullException("relyingParty");
            Protocol protocol = provider.Protocol;
            string signed = query[protocol.openid.signed];

            if (signed == null)
                // #XXX: oidutil.log('No signature present; checkAuth aborted')
                return null;

            // Arguments that are always passed to the server and not
            // included in the signature.
            string[] whitelist = new string[] { protocol.openidnp.assoc_handle, protocol.openidnp.sig, protocol.openidnp.signed, protocol.openidnp.invalidate_handle };
            string[] splitted = signed.Split(',');

            // combine the previous 2 arrays (whitelist + splitted) into a new array: signed_array
            string[] signed_array = new string[whitelist.Length + splitted.Length];
            Array.Copy(whitelist, signed_array, whitelist.Length);
            Array.Copy(splitted, 0, signed_array, whitelist.Length, splitted.Length);

            var check_args = new Dictionary<string, string>();

            foreach (string key in query.Keys) {
                if (key.StartsWith(protocol.openid.Prefix, StringComparison.OrdinalIgnoreCase)
                    && Array.IndexOf(signed_array, key.Substring(protocol.openid.Prefix.Length)) > -1)
                    check_args[key] = query[key];
            }
            check_args[protocol.openid.mode] = protocol.Args.Mode.check_authentication;

            return new CheckAuthRequest(relyingParty, provider, check_args);
        }
        public override string GetLocalPath(IExecutionContext executionContext, ServiceEndpoint endpoint, string path)
        {
            Trace.Verbose("Entering SvnSourceProvider.GetLocalPath");

            ISvnCommandManager svn = HostContext.CreateService<ISvnCommandManager>();
            svn.Init(executionContext, endpoint, CancellationToken.None);

            // We assume that this is a server path first.
            string serverPath = svn.NormalizeRelativePath(path, '/', '\\').Trim();
            string localPath;

            if (serverPath.StartsWith("^/"))
            {
                //Convert the server path to the relative one using SVN work copy mappings
                string sourcesDirectory = executionContext.Variables.Build_SourcesDirectory;
                localPath = svn.ResolveServerPath(serverPath, sourcesDirectory);
            }
            else
            {
                // normalize the path back to the local file system one.
                localPath = svn.NormalizeRelativePath(serverPath, Path.DirectorySeparatorChar, '/');
            }

            Trace.Verbose("Leaving SvnSourceProvider.GetLocalPath");
            return localPath;
        }
Beispiel #8
0
        public static VssCredentials GetVssCredential(ServiceEndpoint serviceEndpoint)
        {
            ArgUtil.NotNull(serviceEndpoint, nameof(serviceEndpoint));
            ArgUtil.NotNull(serviceEndpoint.Authorization, nameof(serviceEndpoint.Authorization));
            ArgUtil.NotNullOrEmpty(serviceEndpoint.Authorization.Scheme, nameof(serviceEndpoint.Authorization.Scheme));

            if (serviceEndpoint.Authorization.Parameters.Count == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(serviceEndpoint));
            }

            VssCredentials credentials = null;
            string accessToken;
            if (serviceEndpoint.Authorization.Scheme == EndpointAuthorizationSchemes.OAuth &&
                serviceEndpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.AccessToken, out accessToken))
            {
                //TODO: consume the new Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential
                //when it is available in the rest SDK
#pragma warning disable 618
                credentials = new VssOAuthCredential(accessToken);
#pragma warning restore 618
            }

            return credentials;
        }
 protected virtual void OnSending(ServiceEndpoint provider, IDictionary<string, string> fields)
 {
     var sending = Sending;
     if (sending != null) {
         sending(provider, fields);
     }
 }
        public async Task GetSourceAsync(IExecutionContext executionContext, ServiceEndpoint endpoint, CancellationToken cancellationToken)
        {
            Trace.Verbose("Entering SvnSourceProvider.GetSourceAsync");

            // Validate args.
            ArgUtil.NotNull(executionContext, nameof(executionContext));
            ArgUtil.NotNull(endpoint, nameof(endpoint));

            ISvnCommandManager svn = HostContext.CreateService<ISvnCommandManager>();
            svn.Init(executionContext, endpoint, cancellationToken);

            // Determine the sources directory.
            string sourcesDirectory = executionContext.Variables.Build_SourcesDirectory;
            executionContext.Debug($"sourcesDirectory={sourcesDirectory}");
            ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory));

            string sourceBranch = executionContext.Variables.Build_SourceBranch;
            executionContext.Debug($"sourceBranch={sourceBranch}");

            string revision = executionContext.Variables.Build_SourceVersion;
            if (string.IsNullOrWhiteSpace(revision))
            {
                revision = "HEAD";
            }
            executionContext.Debug($"revision={revision}");

            bool clean = endpoint.Data.ContainsKey(WellKnownEndpointData.Clean) &&
                StringUtil.ConvertToBoolean(endpoint.Data[WellKnownEndpointData.Clean], defaultValue: false);
            executionContext.Debug($"clean={clean}");

            // Get the definition mappings.
            List<SvnMappingDetails> allMappings = JsonConvert.DeserializeObject<SvnWorkspace>(endpoint.Data[WellKnownEndpointData.SvnWorkspaceMapping]).Mappings;

            if (executionContext.Variables.System_Debug.HasValue && executionContext.Variables.System_Debug.Value)
            {
                allMappings.ForEach(m => executionContext.Debug($"ServerPath: {m.ServerPath}, LocalPath: {m.LocalPath}, Depth: {m.Depth}, Revision: {m.Revision}, IgnoreExternals: {m.IgnoreExternals}"));
            }

            Dictionary<string, SvnMappingDetails> normalizedMappings = svn.NormalizeMappings(allMappings);
            if (executionContext.Variables.System_Debug.HasValue && executionContext.Variables.System_Debug.Value)
            {
                executionContext.Debug($"Normalized mappings count: {normalizedMappings.Count}");
                normalizedMappings.ToList().ForEach(p => executionContext.Debug($"    [{p.Key}] ServerPath: {p.Value.ServerPath}, LocalPath: {p.Value.LocalPath}, Depth: {p.Value.Depth}, Revision: {p.Value.Revision}, IgnoreExternals: {p.Value.IgnoreExternals}"));
            }

            string normalizedBranch = svn.NormalizeRelativePath(sourceBranch, '/', '\\');

            executionContext.Output(StringUtil.Loc("SvnSyncingRepo", endpoint.Name));

            string effectiveRevision = await svn.UpdateWorkspace(
                sourcesDirectory,
                normalizedMappings,
                clean,
                normalizedBranch,
                revision);

            executionContext.Output(StringUtil.Loc("SvnBranchCheckedOut", normalizedBranch, endpoint.Name, effectiveRevision));
            Trace.Verbose("Leaving SvnSourceProvider.GetSourceAsync");
        }
		public IDictionary<string, string> SendDirectMessageAndGetResponse(ServiceEndpoint providerEndpoint, IDictionary<string, string> fields) {
			OpenIdProvider provider = new OpenIdProvider(providerStore, providerEndpoint.ProviderEndpoint,
				providerEndpoint.ProviderEndpoint, fields.ToNameValueCollection());
			Debug.Assert(provider.Request.IsResponseReady, "Direct messages should always have an immediately available response.");
			Response webResponse = (Response)provider.Request.Response;
			EncodableResponse opAuthResponse = (EncodableResponse)webResponse.EncodableMessage;
			return opAuthResponse.EncodedFields;
		}
        public void WithPort_Valid()
        {
            var before = new ServiceEndpoint("host", 10);
            var after = before.WithPort(20);

            Assert.Equal(before.Host, after.Host);
            Assert.Equal(10, before.Port);
            Assert.Equal(20, after.Port);
        }
 public void Init()
 {
     fixture = new Fixture();
     spanCollectorBuilder = MockRepository.GenerateStub<ISpanCollectorBuilder>();
     zipkinEndpoint = MockRepository.GenerateStub<ServiceEndpoint>();
     traceProvider = MockRepository.GenerateStub<ITraceProvider>();
     logger = MockRepository.GenerateStub<IMDLogger>();
     requestName = fixture.Create<string>();
 }
        public void WithHost_Valid()
        {
            var before = new ServiceEndpoint("before", 10);
            var after = before.WithHost("after");

            Assert.Equal(before.Port, after.Port);
            Assert.Equal("before", before.Host);
            Assert.Equal("after", after.Host);
        }
Beispiel #15
0
		internal static void RegisterMockXrdsResponse(ServiceEndpoint endpoint) {
			if (endpoint == null) throw new ArgumentNullException("endpoint");

			string identityUri;
			if (endpoint.ClaimedIdentifier == endpoint.Protocol.ClaimedIdentifierForOPIdentifier) {
				identityUri = endpoint.UserSuppliedIdentifier;
			} else {
				identityUri = endpoint.UserSuppliedIdentifier ?? endpoint.ClaimedIdentifier;
			}
			RegisterMockXrdsResponse(new Uri(identityUri), new ServiceEndpoint[] { endpoint });
		}
 internal ChannelEndpointElement WriteChannelDescription(ServiceEndpoint endpoint, string typeName)
 {
     ChannelEndpointElement element = null;
     BindingDictionaryValue value2 = this.CreateBindingConfig(endpoint.Binding);
     element = new ChannelEndpointElement(endpoint.Address, typeName);
     element.Name = NamingHelper.GetUniqueName(NamingHelper.CodeName(endpoint.Name), new NamingHelper.DoesNameExist(this.CheckIfChannelNameInUse), null);
     element.BindingConfiguration = value2.BindingName;
     element.Binding = value2.BindingSectionName;
     this.channels.Add(element);
     return element;
 }
Beispiel #17
0
		protected DirectRequest(OpenIdRelyingParty relyingParty, ServiceEndpoint provider, IDictionary<string, string> args) {
			if (relyingParty == null) throw new ArgumentNullException("relyingParty");
			if (provider == null) throw new ArgumentNullException("provider");
			if (args == null) throw new ArgumentNullException("args");
			RelyingParty = relyingParty;
			Provider = provider;
			Args = args;
			if (Protocol.QueryDeclaredNamespaceVersion != null &&
				!Args.ContainsKey(Protocol.openid.ns))
				Args.Add(Protocol.openid.ns, Protocol.QueryDeclaredNamespaceVersion);
		}
        public void GetEndpoint()
        {
            var serviceName = fixture.Create<string>();

            var zipkinEndpoint = new ServiceEndpoint();
            var endpoint = zipkinEndpoint.GetEndpoint(serviceName);

            Assert.IsNotNull(endpoint);
            Assert.AreEqual(serviceName, endpoint.Service_name);
            Assert.IsNotNull(endpoint.Ipv4);
            Assert.IsNotNull(endpoint.Port);
        }
Beispiel #19
0
    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        foreach (ClientOperation clientOperation in clientRuntime.ClientOperations)
        {
            if (clientOperation.Name == "TestFaultWithKnownType")
            {
                testFaultWithKnownTypeClientOp = clientOperation;
                return;
            }
        }

        throw new Exception("Expected TestFaultWithKnownType in the ClientOperations, Actual:  TestFaultWithKnownType NOT Found");
    }
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticationRequest"/> class.
        /// </summary>
        /// <param name="endpoint">The endpoint that describes the OpenID Identifier and Provider that will complete the authentication.</param>
        /// <param name="realm">The realm, or root URL, of the host web site.</param>
        /// <param name="returnToUrl">The base return_to URL that the Provider should return the user to to complete authentication.  This should not include callback parameters as these should be added using the <see cref="AddCallbackArguments(string, string)"/> method.</param>
        /// <param name="relyingParty">The relying party that created this instance.</param>
        private AuthenticationRequest(ServiceEndpoint endpoint, Realm realm, Uri returnToUrl, OpenIdRelyingParty relyingParty)
        {
            ErrorUtilities.VerifyArgumentNotNull(endpoint, "endpoint");
            ErrorUtilities.VerifyArgumentNotNull(realm, "realm");
            ErrorUtilities.VerifyArgumentNotNull(returnToUrl, "returnToUrl");
            ErrorUtilities.VerifyArgumentNotNull(relyingParty, "relyingParty");

            this.endpoint = endpoint;
            this.RelyingParty = relyingParty;
            this.Realm = realm;
            this.ReturnToUrl = returnToUrl;

            this.Mode = AuthenticationRequestMode.Setup;
        }
Beispiel #21
0
        public static AssociateRequest Create(OpenIdRelyingParty relyingParty, ServiceEndpoint provider, string assoc_type, string session_type, bool allowNoSession)
        {
            if (relyingParty == null) throw new ArgumentNullException("relyingParty");
            if (provider == null) throw new ArgumentNullException("provider");
            if (assoc_type == null) throw new ArgumentNullException("assoc_type");
            if (session_type == null) throw new ArgumentNullException("session_type");
            Debug.Assert(Array.IndexOf(provider.Protocol.Args.SignatureAlgorithm.All, assoc_type) >= 0);
            Debug.Assert(Array.IndexOf(provider.Protocol.Args.SessionType.All, session_type) >= 0);

            if (!HmacShaAssociation.IsDHSessionCompatible(provider.Protocol, assoc_type, session_type)) {
                throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
                    Strings.IncompatibleAssociationAndSessionTypes, assoc_type, session_type));
            }

            var args = new Dictionary<string, string>();
            Protocol protocol = provider.Protocol;

            args.Add(protocol.openid.mode, protocol.Args.Mode.associate);
            args.Add(protocol.openid.assoc_type, assoc_type);

            DiffieHellman dh = null;

            if (provider.ProviderEndpoint.Scheme == Uri.UriSchemeHttps && allowNoSession) {
                Logger.InfoFormat("Requesting association with {0} (assoc_type = '{1}', session_type = '{2}').",
                        provider.ProviderEndpoint, assoc_type, protocol.Args.SessionType.NoEncryption);
                args.Add(protocol.openid.session_type, protocol.Args.SessionType.NoEncryption);
            } else {
                Logger.InfoFormat("Requesting association with {0} (assoc_type = '{1}', session_type = '{2}').",
                        provider.ProviderEndpoint, assoc_type, session_type);

                // Initiate Diffie-Hellman Exchange
                dh = DiffieHellmanUtil.CreateDiffieHellman();

                byte[] dhPublic = dh.CreateKeyExchange();
                string cpub = DiffieHellmanUtil.UnsignedToBase64(dhPublic);

                args.Add(protocol.openid.session_type, session_type);
                args.Add(protocol.openid.dh_consumer_public, cpub);

                DHParameters dhps = dh.ExportParameters(true);

                if (dhps.P != DiffieHellmanUtil.DEFAULT_MOD || dhps.G != DiffieHellmanUtil.DEFAULT_GEN) {
                    args.Add(protocol.openid.dh_modulus, DiffieHellmanUtil.UnsignedToBase64(dhps.P));
                    args.Add(protocol.openid.dh_gen, DiffieHellmanUtil.UnsignedToBase64(dhps.G));
                }
            }

            return new AssociateRequest(relyingParty, provider, args, dh);
        }
Beispiel #22
0
		public static AssociateRequest Create(OpenIdRelyingParty relyingParty, ServiceEndpoint provider) {
			if (relyingParty == null) throw new ArgumentNullException("relyingParty");
			if (provider == null) throw new ArgumentNullException("provider");

			string assoc_type, session_type;
			if (HmacShaAssociation.TryFindBestAssociation(provider.Protocol,
				relyingParty.Settings.MinimumHashBitLength, relyingParty.Settings.MaximumHashBitLength,
				true, out assoc_type, out session_type)) {
				return Create(relyingParty, provider, assoc_type, session_type, true);
			} else {
				// There are no associations that meet all requirements.
				Logger.Warn("Security requirements and protocol combination knock out all possible association types.  Dumb mode forced.");
				return null;
			}
		}
        public void ShouldDisposeSourcesAndPublishers()
        {
            IMessageSource<IRequest> requestSource = A.Fake<IMessageSource<IRequest>>();
            IMessageSource<ICommand> commandSource = A.Fake<IMessageSource<ICommand>>();
            IMessagePublisher<IEvent> eventPublisher = A.Fake<IMessagePublisher<IEvent>>();
            IMessagePublisher<IResponse> responsePublisher = A.Fake<IMessagePublisher<IResponse>>();
            IServiceEndpoint endpoint = new ServiceEndpoint(requestSource, commandSource, eventPublisher, responsePublisher, typeof(ITestServiceMessage1));

            endpoint.Dispose();

            A.CallTo(() => requestSource.Dispose()).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => commandSource.Dispose()).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => eventPublisher.Dispose()).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => responsePublisher.Dispose()).MustHaveHappened(Repeated.Exactly.Once);
        }
Beispiel #24
0
        public TrackingConfig(IExecutionContext executionContext, ServiceEndpoint endpoint, int buildDirectory, string hashKey)
        {
            // Set the directories.
            BuildDirectory = buildDirectory.ToString(CultureInfo.InvariantCulture);
            ArtifactsDirectory = Path.Combine(BuildDirectory, Constants.Build.Path.ArtifactsDirectory);
            SourcesDirectory = Path.Combine(BuildDirectory, Constants.Build.Path.SourcesDirectory);
            TestResultsDirectory = Path.Combine(BuildDirectory, Constants.Build.Path.TestResultsDirectory);

            // Set the other properties.
            CollectionId = executionContext.Variables.System_CollectionId;
            DefinitionId = executionContext.Variables.System_DefinitionId;
            HashKey = hashKey;
            RepositoryUrl = endpoint.Url.AbsoluteUri;
            System = BuildSystem;
            UpdateJobRunProperties(executionContext);
        }
		AuthenticationRequest(ServiceEndpoint endpoint,
			Realm realm, Uri returnToUrl, OpenIdRelyingParty relyingParty) {
			if (endpoint == null) throw new ArgumentNullException("endpoint");
			if (realm == null) throw new ArgumentNullException("realm");
			if (returnToUrl == null) throw new ArgumentNullException("returnToUrl");
			if (relyingParty == null) throw new ArgumentNullException("relyingParty");

			this.endpoint = endpoint;
			RelyingParty = relyingParty;
			Realm = realm;
			ReturnToUrl = returnToUrl;

			Mode = AuthenticationRequestMode.Setup;
			OutgoingExtensions = ExtensionArgumentsManager.CreateOutgoingExtensions(endpoint.Protocol);
			ReturnToArgs = new Dictionary<string, string>();
		}
		public void ApplyClientBehavior (ServiceEndpoint endpoint, ClientRuntime clientRuntime)
		{
			ClientBehaviorApplied = true;

			var inspector = new MessageInspector ();
			inspector.RequestSending += delegate (ref Message message, IClientChannel channel) {
				if (RequestSending != null)
					return RequestSending (ref message, channel);
				else
					return null;
			};
			inspector.ReplyReceived += delegate (ref Message reply, object correlationState) {
				if (ReplyReceived != null)
					ReplyReceived (ref reply, correlationState);
			};
			clientRuntime.MessageInspectors.Add (inspector);
		}
		public void ApplyDispatchBehavior (ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
		{
			DispatchBehaviorApplied = true;

			var inspector = new DispatchMessageInspector ();
			inspector.RequestReceived += delegate (ref Message message, IClientChannel channel, InstanceContext instanceContext) {
				if (RequestReceived != null)
					return RequestReceived (ref message, channel, instanceContext);
				else
					return null;
			};
			inspector.ReplySending += delegate (ref Message reply, object correlationState) {
				if (ReplySending != null)
					ReplySending (ref reply, correlationState);
			};
			endpointDispatcher.DispatchRuntime.MessageInspectors.Add (inspector);
		}
        public void Init(
            IExecutionContext context,
            ServiceEndpoint endpoint,
            CancellationToken cancellationToken)
        {
            // Validation.
            ArgUtil.NotNull(context, nameof(context));
            ArgUtil.NotNull(endpoint, nameof(endpoint));
            ArgUtil.NotNull(cancellationToken, nameof(cancellationToken));

            ArgUtil.NotNull(endpoint.Url, nameof(endpoint.Url));
            ArgUtil.Equal(true, endpoint.Url.IsAbsoluteUri, nameof(endpoint.Url.IsAbsoluteUri));
            ArgUtil.NotNull(endpoint.Data, nameof(endpoint.Data));

            ArgUtil.NotNull(endpoint.Authorization, nameof(endpoint.Authorization));
            ArgUtil.NotNull(endpoint.Authorization.Parameters, nameof(endpoint.Authorization.Parameters));
            ArgUtil.Equal(EndpointAuthorizationSchemes.UsernamePassword, endpoint.Authorization.Scheme, nameof(endpoint.Authorization.Scheme));

            _context = context;
            _endpoint = endpoint;
            _cancellationToken = cancellationToken;

            // Find svn in %Path%
            IWhichUtil whichTool = HostContext.GetService<IWhichUtil>();
            string svnPath = whichTool.Which("svn");

            if (string.IsNullOrEmpty(svnPath))
            {
                throw new Exception(StringUtil.Loc("SvnNotInstalled"));
            }
            else
            {
                _context.Debug($"Found svn installation path: {svnPath}.");
                _svn = svnPath;
            }

            // External providers may need basic auth or tokens
            endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Username, out _username);
            endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Password, out _password);

            // TODO: replace explicit string literals with WellKnownEndpointData constants 
            // as soon as the latters are available thru the Microsoft.TeamFoundation.Build.WebApi package

            _acceptUntrusted = endpoint.Data.ContainsKey(/* WellKnownEndpointData.SvnAcceptUntrustedCertificates */ "acceptUntrustedCerts") &&
            StringUtil.ConvertToBoolean(endpoint.Data[/* WellKnownEndpointData.SvnAcceptUntrustedCertificates */ "acceptUntrustedCerts"], defaultValue: false);
        }
        public IDictionary<string, string> SendDirectMessageAndGetResponse(ServiceEndpoint provider, IDictionary<string, string> fields)
        {
            if (provider == null) throw new ArgumentNullException("provider");
            if (fields == null) throw new ArgumentNullException("fields");

            byte[] body = ProtocolMessages.Http.GetBytes(fields);
            IDictionary<string, string> args;
            UntrustedWebResponse resp = null;
            string fullResponseText = null;
            try {
                resp = UntrustedWebRequest.Request(provider.ProviderEndpoint, body);
                // If an internal server error occurred, there won't be any KV-form stream
                // to read in.  So instead, preserve whatever error the server did send back
                // and throw it in the exception.
                if (resp.StatusCode == HttpStatusCode.InternalServerError) {
                    string errorStream = new StreamReader(resp.ResponseStream).ReadToEnd();
                    throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
                        Strings.ProviderRespondedWithError, errorStream));
                }
                if (Logger.IsDebugEnabled) {
                    fullResponseText = resp.ReadResponseString();
                }
                args = ProtocolMessages.KeyValueForm.GetDictionary(resp.ResponseStream);
                Logger.DebugFormat("Received direct response from {0}: {1}{2}", provider.ProviderEndpoint,
                    Environment.NewLine, Util.ToString(args));
            } catch (ArgumentException e) {
                Logger.DebugFormat("Full response from provider (where KVF was expected):{0}{1}",
                    Environment.NewLine, fullResponseText);
                throw new OpenIdException("Failure decoding Key-Value Form response from provider.", e);
            } catch (WebException e) {
                throw new OpenIdException("Failure while connecting to provider.", e);
            }
            // All error codes are supposed to be returned with 400, but
            // some (like myopenid.com) sometimes send errors as 200's.
            if (resp.StatusCode == HttpStatusCode.BadRequest ||
                Util.GetOptionalArg(args, provider.Protocol.openidnp.mode) == provider.Protocol.Args.Mode.error) {
                throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
                    Strings.ProviderRespondedWithError,
                    Util.GetOptionalArg(args, provider.Protocol.openidnp.error)), args);
            } else if (resp.StatusCode == HttpStatusCode.OK) {
                return args;
            } else {
                throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
                    Strings.ProviderRespondedWithUnrecognizedHTTPStatusCode, resp.StatusCode));
            }
        }
        AuthenticationRequest(string token, Association assoc, ServiceEndpoint endpoint,
            Realm realm, Uri returnToUrl, OpenIdRelyingParty relyingParty)
        {
            if (endpoint == null) throw new ArgumentNullException("endpoint");
            if (realm == null) throw new ArgumentNullException("realm");
            if (returnToUrl == null) throw new ArgumentNullException("returnToUrl");
            if (relyingParty == null) throw new ArgumentNullException("relyingParty");

            this.assoc = assoc;
            this.endpoint = endpoint;
            RelyingParty = relyingParty;
            Realm = realm;
            ReturnToUrl = returnToUrl;

            Mode = AuthenticationRequestMode.Setup;
            OutgoingExtensions = ExtensionArgumentsManager.CreateOutgoingExtensions(endpoint.Protocol);
            ReturnToArgs = new Dictionary<string, string>();
            if (token != null)
                AddCallbackArguments(DotNetOpenId.RelyingParty.Token.TokenKey, token);
        }
Beispiel #31
0
 protected override void OnApplyConfiguration(ServiceEndpoint endpoint, ServiceEndpointElement serviceEndpointElement)
 {
 }
 public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
 {
 }
Beispiel #33
0
        public void AddECSContainerSupport_configuration_throws_if_endpoint_has_no_address(ServiceCollection services, IConfiguration configuration, ServiceEndpoint endpoint)
        {
            AddFakeContainerMetadataFileKey();

            ECSMetadataExtensions.AddECSContainerSupport(services, configuration);

            var serviceProvider = services.BuildServiceProvider();

            var options = serviceProvider.GetRequiredService <IOptions <AnnouncementServiceOptions> >();

            Assert.Throws <ArgumentNullException>(() => options.Value.EndpointDiscoveryMetadata(endpoint));
        }
Beispiel #34
0
 public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
 {
     // Set AddressFilter to CultureHeaderFilter
     endpointDispatcher.AddressFilter =
         new CultureHeaderFilter(); 
 }
Beispiel #35
0
 public void SetEndpointAddress(ServiceEndpoint endpoint, string relativeAddress)
 {
     throw new PlatformNotSupportedException();
 }
 public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
 {
     clientRuntime.ClientMessageInspectors.Add(new JwtHeaderMessageInspector(_options, _userToken));
 }
Beispiel #37
0
        public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            AutoPoolInspector <T> inspector = new AutoPoolInspector <T>(client);

            clientRuntime.MessageInspectors.Add(inspector);
        }
 public void Validate(ServiceEndpoint endpoint)
 {
 }
        private void AddPreflightOperations(ServiceEndpoint endpoint, List <OperationDescription> corsOperations)
        {
            Dictionary <string, PreflightOperationBehavior> uriTemplates = new Dictionary <string, PreflightOperationBehavior>(StringComparer.OrdinalIgnoreCase);

            foreach (var operation in corsOperations)
            {
                if (operation.Behaviors.Find <WebGetAttribute>() != null)
                {
                    // no need to add preflight operation for GET requests
                    continue;
                }

                if (operation.IsOneWay)
                {
                    // no support for 1-way messages
                    continue;
                }

                string             originalUriTemplate;
                WebInvokeAttribute originalWia = operation.Behaviors.Find <WebInvokeAttribute>();

                if (originalWia != null && originalWia.UriTemplate != null)
                {
                    originalUriTemplate = NormalizeTemplate(originalWia.UriTemplate);
                }
                else
                {
                    originalUriTemplate = operation.Name;
                }

                string originalMethod = originalWia != null && originalWia.Method != null ? originalWia.Method : "POST";

                if (uriTemplates.ContainsKey(originalUriTemplate))
                {
                    // there is already an OPTIONS operation for this URI, we can reuse it
                    PreflightOperationBehavior operationBehavior = uriTemplates[originalUriTemplate];
                    operationBehavior.AddAllowedMethod(originalMethod);
                }
                else
                {
                    ContractDescription  contract           = operation.DeclaringContract;
                    OperationDescription preflightOperation = new OperationDescription(operation.Name + CorsConstants.PreflightSuffix, contract);
                    MessageDescription   inputMessage       = new MessageDescription(operation.Messages[0].Action + CorsConstants.PreflightSuffix, MessageDirection.Input);
                    inputMessage.Body.Parts.Add(new MessagePartDescription("input", contract.Namespace)
                    {
                        Index = 0, Type = typeof(Message)
                    });
                    preflightOperation.Messages.Add(inputMessage);
                    MessageDescription outputMessage = new MessageDescription(operation.Messages[1].Action + CorsConstants.PreflightSuffix, MessageDirection.Output);
                    outputMessage.Body.ReturnValue = new MessagePartDescription(preflightOperation.Name + "Return", contract.Namespace)
                    {
                        Type = typeof(Message)
                    };
                    preflightOperation.Messages.Add(outputMessage);

                    WebInvokeAttribute wia = new WebInvokeAttribute();
                    wia.UriTemplate = originalUriTemplate;
                    wia.Method      = "OPTIONS";

                    preflightOperation.Behaviors.Add(wia);
                    preflightOperation.Behaviors.Add(new DataContractSerializerOperationBehavior(preflightOperation));
                    PreflightOperationBehavior preflightOperationBehavior = new PreflightOperationBehavior(preflightOperation);
                    preflightOperationBehavior.AddAllowedMethod(originalMethod);
                    preflightOperation.Behaviors.Add(preflightOperationBehavior);
                    uriTemplates.Add(originalUriTemplate, preflightOperationBehavior);

                    contract.Operations.Add(preflightOperation);
                }
            }
        }
        public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            OAuth2HeaderInspector inspector = new OAuth2HeaderInspector();

            clientRuntime.MessageInspectors.Add(inspector);
        }
 public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
 {
 }
 public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
 {
 }
 public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
 {
 }
 public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
 {
     clientRuntime.MessageInspectors.Add(this);
 }
 public void Validate(ServiceEndpoint endpoint)
 {
     // for future use
 }
 public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
 {
 }
 public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
 {
     // for future use
 }
Beispiel #48
0
        public void Execute(IExecutionContext context, Command command)
        {
            ArgUtil.NotNull(context, nameof(context));
            ArgUtil.NotNull(context.Endpoints, nameof(context.Endpoints));
            ArgUtil.NotNull(command, nameof(command));

            var eventProperties = command.Properties;
            var data            = command.Data;

            ServiceEndpoint systemConnection = context.Endpoints.FirstOrDefault(e => string.Equals(e.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase));

            ArgUtil.NotNull(systemConnection, nameof(systemConnection));
            ArgUtil.NotNull(systemConnection.Url, nameof(systemConnection.Url));

            Uri            projectUrl        = systemConnection.Url;
            VssCredentials projectCredential = VssUtil.GetVssCredential(systemConnection);

            Guid projectId = context.Variables.System_TeamProjectId ?? Guid.Empty;

            ArgUtil.NotEmpty(projectId, nameof(projectId));

            int?buildId = context.Variables.Build_BuildId;

            ArgUtil.NotNull(buildId, nameof(buildId));

            string artifactName;

            if (!eventProperties.TryGetValue(ArtifactAssociateEventProperties.ArtifactName, out artifactName) ||
                string.IsNullOrEmpty(artifactName))
            {
                throw new Exception(StringUtil.Loc("ArtifactNameRequired"));
            }

            string artifactType;

            if (!eventProperties.TryGetValue(ArtifactAssociateEventProperties.ArtifactType, out artifactType))
            {
                artifactType = ArtifactCommandExtensionUtil.InferArtifactResourceType(context, data);
            }

            if (string.IsNullOrEmpty(artifactType))
            {
                throw new Exception(StringUtil.Loc("ArtifactTypeRequired"));
            }
            else if ((artifactType.Equals(ArtifactResourceTypes.Container, StringComparison.OrdinalIgnoreCase) ||
                      artifactType.Equals(ArtifactResourceTypes.FilePath, StringComparison.OrdinalIgnoreCase) ||
                      artifactType.Equals(ArtifactResourceTypes.VersionControl, StringComparison.OrdinalIgnoreCase)) &&
                     string.IsNullOrEmpty(data))
            {
                throw new Exception(StringUtil.Loc("ArtifactLocationRequired"));
            }

            if (!artifactType.Equals(ArtifactResourceTypes.FilePath, StringComparison.OrdinalIgnoreCase) &&
                context.Variables.System_HostType != HostTypes.Build)
            {
                throw new Exception(StringUtil.Loc("AssociateArtifactCommandNotSupported", context.Variables.System_HostType));
            }

            var propertyDictionary = ArtifactCommandExtensionUtil.ExtractArtifactProperties(eventProperties);

            string artifactData = "";

            if (ArtifactCommandExtensionUtil.IsContainerPath(data) ||
                ArtifactCommandExtensionUtil.IsValidServerPath(data))
            {
                //if data is a file container path or a tfvc server path
                artifactData = data;
            }
            else if (ArtifactCommandExtensionUtil.IsUncSharePath(context, data))
            {
                //if data is a UNC share path
                artifactData = new Uri(data).LocalPath;
            }
            else
            {
                artifactData = data ?? string.Empty;
            }

            // queue async command task to associate artifact.
            context.Debug($"Associate artifact: {artifactName} with build: {buildId.Value} at backend.");
            var commandContext = context.GetHostContext().CreateService <IAsyncCommandContext>();

            commandContext.InitializeCommandContext(context, StringUtil.Loc("AssociateArtifact"));
            commandContext.Task = ArtifactCommandExtensionUtil.AssociateArtifactAsync(commandContext,
                                                                                      WorkerUtilities.GetVssConnection(context),
                                                                                      projectId,
                                                                                      buildId.Value,
                                                                                      artifactName,
                                                                                      context.Variables.System_JobId,
                                                                                      artifactType,
                                                                                      artifactData,
                                                                                      propertyDictionary,
                                                                                      context.CancellationToken);
            context.AsyncCommands.Add(commandContext);
        }
Beispiel #49
0
 public Factory(ServiceEndpoint endpoint) : base(endpoint)
 {
 }
Beispiel #50
0
 public virtual void AddServiceEndpoint(ServiceEndpoint endpoint)
 {
     throw new PlatformNotSupportedException();
 }
Beispiel #51
0
 public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
 {}
Beispiel #52
0
 public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
 {
     endpointDispatcher.DispatchRuntime.InstanceContextInitializers.Add(this);
 }
        /// <summary>
        /// Create a new service client instance of the <typeparamref name="TContract"/> using the specified  <see cref="T:System.ServiceModel.InstanceContext"/> and  <see cref="T:System.ServiceModel.Description.ServiceEndpoint"/> objects.
        /// </summary>
        /// <param name="callbackInstance">The callback object that the client application uses to listen for messages from the connected service.</param>
        /// <param name="endpoint">The endpoint for a service that allows clients to find and communicate with the service.</param>
        public static TContract GetService <TContract>(InstanceContext callbackInstance, ServiceEndpoint endpoint)
        {
            var serviceType = GetServiceType(typeof(TContract));

            if (serviceType == null)
            {
                return(default(TContract));
            }
            return((TContract)Activator.CreateInstance(serviceType, callbackInstance, endpoint));
        }
 public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
 {
 }
Beispiel #55
0
        public void AddECSContainerSupport_configuration_returns_metadata_with_same_if_no_mapping(ServiceCollection services, [Frozen] ECSContainerMetadata containerMetadata, IConfiguration configuration, ServiceEndpoint endpoint, int port, string address)
        {
            AddFakeContainerMetadataFileKey();

            var expectedAddress = new Uri($"http://{containerMetadata.HostPrivateIPv4Address}:{port}/{address}");

            endpoint.Address = new EndpointAddress($"http://localhost:{port}/{address}");

            ECSMetadataExtensions.AddECSContainerSupport(services, configuration);

            var serviceProvider = services.BuildServiceProvider();

            var options = serviceProvider.GetRequiredService <IOptions <AnnouncementServiceOptions> >();

            var result = options.Value.EndpointDiscoveryMetadata(endpoint);

            Assert.That(result.Address.Uri, Is.EqualTo(expectedAddress).IgnoreCase);
        }
 public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.DispatchRuntime dispatchRuntime)
 {
 }
Beispiel #57
0
 protected override void OnApplyConfiguration(ServiceEndpoint endpoint, ServiceEndpointElement serviceEndpointElement)
 {
     throw new NotImplementedException();
 }
Beispiel #58
0
        public void AddECSContainerSupport_configuration_returns_metadata_with_same_address_when_ecs_metadata_has_no_ipv4_address(ServiceCollection services, IConfiguration configuration, ServiceEndpoint endpoint, int port, string address)
        {
            AddFakeContainerMetadataFileKey();

            configuration[nameof(ECSContainerMetadata.HostPrivateIPv4Address)] = null;

            endpoint.Address = new EndpointAddress($"http://localhost:{port}/{address}");

            ECSMetadataExtensions.AddECSContainerSupport(services, configuration);

            var serviceProvider = services.BuildServiceProvider();

            var options = serviceProvider.GetRequiredService <IOptions <AnnouncementServiceOptions> >();

            var result = options.Value.EndpointDiscoveryMetadata(endpoint);

            Assert.That(result.Address.Uri, Is.EqualTo(endpoint.Address.Uri));
        }
 public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
 {
 }
Beispiel #60
0
        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            var inspector = new NewRelicClientMessageInspector(_agent, _bindingType);

            clientRuntime.ClientMessageInspectors.Add(inspector);
        }