public void UsernameIsSetCorrectly(string expected, string password)
        {
            var sut = new ServiceIdentity(expected, password);

            var actual = sut.UserName;

            Assert.Equal(expected, actual);
        }
        public void PasswordIsSetCorrectly(string username, string expected)
        {
            var sut = new ServiceIdentity(username, expected);

            var actual = sut.Password;

            Assert.Equal(expected, actual);
        }
        public void ServiceAccountUsersIsSetBySupplyingLoginAndPass(string username, string password)
        {
            var sut = new ServiceIdentity(username, password);

            var expected = ServiceAccount.User;
            var actual = sut.ServiceAccount;

            Assert.Equal(expected, actual);
        }
 private bool ValidateSourceDemandLimitManager(ServiceIdentity identity, Guid instanceId)
 {
     using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
     {
         using (var context = CreateContext())
         {
             return(context.DemandAdjustments.Count(
                        p =>
                        p.Id == instanceId && p.SourceDemandId.HasValue &&
                        p.SourceDemand.LimitId.HasValue && p.SourceDemand.Limit.ManagerId == identity.Id) == 1);
         }
     }
 }
Пример #5
0
        /// <summary>
        /// 在系统中检查用户登录的凭据是否还在
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool CheckUserIdentity()
        {
            //假设服务上有300个用户,没处理一次,需要9秒左右,加上轮询间隔,总共不超过15秒
            //执行该方法的总的时间必须 小于每个凭据的过期时间
            currentContext.BatchInterval   = 5000;
            currentContext.ParallelExecute = false;

            System.Diagnostics.Debug.WriteLine("--------------CheckUserIdentity Client IP:{0},{1}", this.currentContext.Request.ClientIP, this.currentContext.Request.ClientIdentity);
            ServiceAuthentication auth = new ServiceAuthentication(this.currentContext);
            ServiceIdentity       user = auth.GetIdentity();

            return(user != null);
        }
Пример #6
0
        /// <summary>
        /// 注销登录
        /// </summary>
        /// <returns></returns>
        public bool Logout()
        {
            ServiceAuthentication auth = new ServiceAuthentication(this.currentContext);
            ServiceIdentity       user = auth.GetIdentity();

            if (user != null)
            {
                UserBIZ biz = new UserBIZ();
                biz.SaveLogoutLog(user.Id);
                return(auth.SignOut(user));
            }
            return(false);
        }
        public async Task AuthenticateAsyncWithModuleThumbprintX509InScopeCacheFails()
        {
            string deviceId               = "d1";
            string moduleId               = "m1";
            string identity               = FormattableString.Invariant($"{deviceId}/{moduleId}");
            var    primaryCertificate     = TestCertificateHelper.GenerateSelfSignedCert("primo");
            var    primaryClientCertChain = new List <X509Certificate2>()
            {
                primaryCertificate
            };
            var secondaryCertificate     = TestCertificateHelper.GenerateSelfSignedCert("secondo");
            var secondaryClientCertChain = new List <X509Certificate2>()
            {
                secondaryCertificate
            };

            var deviceScopeIdentitiesCache       = new Mock <IDeviceScopeIdentitiesCache>();
            IList <X509Certificate2> trustBundle = new List <X509Certificate2>();
            var primaryCredentials = Mock.Of <ICertificateCredentials>(
                c =>
                c.Identity == Mock.Of <IModuleIdentity>(
                    i => i.DeviceId == deviceId && i.ModuleId == moduleId &&
                    i.Id == identity) &&
                c.AuthenticationType == AuthenticationType.X509Cert &&
                c.ClientCertificate == primaryCertificate && c.ClientCertificateChain == primaryClientCertChain);

            var secondaryCredentials = Mock.Of <ICertificateCredentials>(
                c =>
                c.Identity == Mock.Of <IModuleIdentity>(
                    i => i.DeviceId == deviceId && i.ModuleId == moduleId &&
                    i.Id == identity) &&
                c.AuthenticationType == AuthenticationType.X509Cert &&
                c.ClientCertificate == secondaryCertificate && c.ClientCertificateChain == secondaryClientCertChain);

            var serviceIdentity = new ServiceIdentity(
                deviceId,
                moduleId,
                "e1",
                new List <string>(),
                "1234",
                new string[0],
                new ServiceAuthentication(new X509ThumbprintAuthentication(primaryCertificate.Thumbprint, secondaryCertificate.Thumbprint)),
                ServiceIdentityStatus.Enabled);
            var authenticator = new DeviceScopeCertificateAuthenticator(deviceScopeIdentitiesCache.Object, UnderlyingAuthenticator, trustBundle, true);

            deviceScopeIdentitiesCache.Setup(d => d.GetServiceIdentity(It.Is <string>(i => i == identity))).ReturnsAsync(Option.Some(serviceIdentity));

            // Assert
            Assert.False(await authenticator.AuthenticateAsync(primaryCredentials));
            Assert.False(await authenticator.AuthenticateAsync(secondaryCredentials));
        }
Пример #8
0
        public async Task <Option <ServiceIdentity> > GetServiceIdentity(string deviceId, string moduleId)
        {
            string id = $"{deviceId}/{moduleId}";
            Option <ScopeResult> scopeResult = Option.None <ScopeResult>();

            try
            {
                ScopeResult res = await this.securityScopesApiClient.GetIdentity(deviceId, moduleId);

                scopeResult = Option.Maybe(res);
                Events.IdentityScopeResultReceived(id);
            }
            catch (DeviceScopeApiException ex) when(ex.StatusCode == HttpStatusCode.BadRequest)
            {
                Events.BadRequestResult(id, ex.StatusCode);
            }

            Option <ServiceIdentity> serviceIdentityResult =
                scopeResult
                .Map(
                    sc =>
            {
                if (sc.Modules != null)
                {
                    int count = sc.Modules.Count();
                    if (count == 1)
                    {
                        ServiceIdentity serviceIdentity = sc.Modules.First().ToServiceIdentity();
                        return(Option.Some(serviceIdentity));
                    }
                    else
                    {
                        Events.UnexpectedResult(count, 1, "modules", id);
                    }
                }
                else
                {
                    Events.NullDevicesResult(id);
                }

                return(Option.None <ServiceIdentity>());
            })
                .GetOrElse(
                    () =>
            {
                Events.NullResult(id);
                return(Option.None <ServiceIdentity>());
            });

            return(serviceIdentityResult);
        }
Пример #9
0
        public void TestHandleServiceIdentityUpdateSuccess()
        {
            // Arrange
            var      connectionManager          = new Mock <IConnectionManager>(MockBehavior.Strict);
            var      authenticator              = new Mock <IAuthenticator>(MockBehavior.Strict);
            var      credentialsStore           = new Mock <ICredentialsCache>(MockBehavior.Strict);
            var      deviceScopeIdentitiesCache = new Mock <IDeviceScopeIdentitiesCache>(MockBehavior.Strict);
            TimeSpan reauthFrequency            = TimeSpan.FromSeconds(3);

            var deviceIdentity = new DeviceIdentity(IoTHubHostName, "d1");
            var moduleIdentity = new ModuleIdentity(IoTHubHostName, "d1", "m1");

            var deviceCredentials = Mock.Of <IClientCredentials>(c => c.Identity == deviceIdentity && c.AuthenticationType == AuthenticationType.SasKey);
            var moduleCredentials = Mock.Of <IClientCredentials>(c => c.Identity == moduleIdentity && c.AuthenticationType == AuthenticationType.SasKey);

            credentialsStore.Setup(c => c.Get(deviceIdentity)).ReturnsAsync(Option.Some(deviceCredentials));
            credentialsStore.Setup(c => c.Get(moduleIdentity)).ReturnsAsync(Option.Some(moduleCredentials));

            var deviceProxy = Mock.Of <IDeviceProxy>(d => d.IsActive && d.Identity == deviceIdentity);
            var moduleProxy = Mock.Of <IDeviceProxy>(d => d.IsActive && d.Identity == moduleIdentity);

            connectionManager.Setup(c => c.GetDeviceConnection("d1")).Returns(Option.Some(deviceProxy));
            connectionManager.Setup(c => c.GetDeviceConnection("d1/m1")).Returns(Option.Some(moduleProxy));

            connectionManager.Setup(c => c.RemoveDeviceConnection("d1")).Returns(Task.CompletedTask);
            connectionManager.Setup(c => c.RemoveDeviceConnection("d1/m1")).Returns(Task.CompletedTask);

            authenticator.Setup(a => a.ReauthenticateAsync(deviceCredentials)).ReturnsAsync(true);
            authenticator.Setup(a => a.ReauthenticateAsync(moduleCredentials)).ReturnsAsync(true);

            var serviceAuthentication = new ServiceAuthentication(ServiceAuthenticationType.None);
            var deviceServiceIdentity = new ServiceIdentity("d1", "1234", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled);
            var moduleServiceIdentity = new ServiceIdentity("d1/m1", "1234", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled);

            // Act
            var connectionReauthenticator = new ConnectionReauthenticator(connectionManager.Object, authenticator.Object, credentialsStore.Object, deviceScopeIdentitiesCache.Object, reauthFrequency, Mock.Of <IIdentity>(e => e.Id == "ed/$edgeHub"));

            deviceScopeIdentitiesCache.Raise(d => d.ServiceIdentityUpdated += null, null, deviceServiceIdentity);
            deviceScopeIdentitiesCache.Raise(d => d.ServiceIdentityUpdated += null, null, moduleServiceIdentity);

            // Assert
            Assert.NotNull(connectionReauthenticator);
            connectionManager.Verify(c => c.RemoveDeviceConnection("d1"), Times.Never);
            connectionManager.Verify(c => c.RemoveDeviceConnection("d1/m1"), Times.Never);
            connectionManager.Verify(c => c.GetDeviceConnection("d1"), Times.Once);
            connectionManager.Verify(c => c.GetDeviceConnection("d1/m1"), Times.Once);
            authenticator.VerifyAll();
            credentialsStore.VerifyAll();
            deviceScopeIdentitiesCache.VerifyAll();
        }
Пример #10
0
        public static EdgeHubScopeDevice ToEdgeHubScopeDevice(this ServiceIdentity identity)
        {
            Preconditions.CheckNotNull(identity);
            Preconditions.CheckArgument(!identity.IsModule);

            return(new EdgeHubScopeDevice(
                       identity.DeviceId,
                       identity.GenerationId,
                       GetDeviceStatus(identity.Status),
                       GetAuthenticationMechanism(identity.Authentication),
                       GetDeviceCapabilities(identity.IsEdgeDevice),
                       identity.DeviceScope.OrDefault(),
                       identity.ParentScopes));
        }
        public async Task ConnectUsingIdentityInCacheTest()
        {
            // Arrange
            var    deviceIdentity = Mock.Of <IDeviceIdentity>(m => m.Id == "d1");
            string token          = TokenHelper.CreateSasToken(IotHubHostName, DateTime.UtcNow.AddMinutes(10));
            var    tokenCreds     = new TokenCredentials(deviceIdentity, token, string.Empty, Option.None <string>(), Option.None <string>(), false);

            var deviceScopeIdentitiesCache = new Mock <IDeviceScopeIdentitiesCache>(MockBehavior.Strict);
            var deviceServiceIdentity      = new ServiceIdentity(deviceIdentity.Id, "1234", new string[0], new ServiceAuthentication(ServiceAuthenticationType.CertificateAuthority), ServiceIdentityStatus.Disabled);

            deviceScopeIdentitiesCache.Setup(d => d.GetServiceIdentity(It.Is <string>(i => i == deviceIdentity.Id)))
            .ReturnsAsync(Option.Some(deviceServiceIdentity));
            deviceScopeIdentitiesCache.Setup(d => d.GetAuthChain(It.Is <string>(i => i == deviceIdentity.Id)))
            .ReturnsAsync(Option.Some(deviceIdentity.Id));

            var credentialsCache = new Mock <ICredentialsCache>(MockBehavior.Strict);

            credentialsCache.Setup(c => c.Get(deviceIdentity)).ReturnsAsync(Option.Some((IClientCredentials)tokenCreds));
            var metadataStore = new Mock <IMetadataStore>();

            metadataStore.Setup(m => m.GetMetadata(It.IsAny <string>())).ReturnsAsync(new ConnectionMetadata("dummyValue"));
            var edgeHub = Mock.Of <IEdgeHub>();
            ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(
                MessageConverterProvider,
                ConnectionPoolSize,
                GetMockDeviceClientProvider(),
                Option.None <UpstreamProtocol>(),
                TokenProvider,
                deviceScopeIdentitiesCache.Object,
                credentialsCache.Object,
                EdgeHubIdentity,
                TimeSpan.FromMinutes(60),
                true,
                TimeSpan.FromSeconds(20),
                false,
                Option.None <IWebProxy>(),
                metadataStore.Object,
                true);

            cloudConnectionProvider.BindEdgeHub(edgeHub);

            // Act
            Try <ICloudConnection> cloudProxy = await cloudConnectionProvider.Connect(deviceIdentity, null);

            // Assert
            Assert.True(cloudProxy.Success);
            Assert.NotNull(cloudProxy.Value);
            deviceScopeIdentitiesCache.VerifyAll();
            credentialsCache.VerifyAll();
        }
        public bool IsCurrentUserAllowedToExecuteCommandInCurrentState(ServiceIdentity identity, WorkflowState state, Guid instanceId)
        {
            if (state == null)
            {
                return(ValidateInitiator(identity, instanceId));
            }

            if (state.Type != WorkflowType.DemandAdjustmentWorkflow)
            {
                return(false);
            }

            if (state == WorkflowState.DemandAdjustmentDraft)
            {
                return(ValidateInitiator(identity, instanceId));
            }

            if (state == WorkflowState.DemandAdjustmentSourceDemandLimitManagerSighting)
            {
                return(ValidateSourceDemandLimitManager(identity, instanceId));
            }

            if (state == WorkflowState.DemandAdjustmentSourceDemandLimitExecutorSighting)
            {
                return(ValidateSourceDemandLimitExecutor(identity, instanceId));
            }

            if (state == WorkflowState.DemandAdjustmentTargetDemandLimitExecutorSighting)
            {
                return(ValidateTargetDemandLimitExecutor(identity, instanceId));
            }

            if (state == WorkflowState.DemandAdjustmentTargetDemandLimitManagerSighting)
            {
                return(ValidateTargetDemandLimitManager(identity, instanceId));
            }

            if (state == WorkflowState.DemandAdjustmentUPKZCuratorSighting)
            {
                return(AuthorizationService.IsInRole(identity.Id, BudgetRole.Curator));
            }

            if (state == WorkflowState.DemandAdjustmentUPKZHeadSighting)
            {
                return(AuthorizationService.IsInRole(identity.Id, BudgetRole.UPKZHead));
            }

            return(false);
        }
Пример #13
0
        void InsertDeviceIdentity(ServiceIdentity device)
        {
            // Root device is the base-case for constructing the authchain,
            // child devices derive their authchain from the parent
            var newNode = device.Id == this.actorDeviceId ?
                          new ServiceIdentityTreeNode(device, Option.Some(this.actorDeviceId)) :
                          new ServiceIdentityTreeNode(device, Option.None <string>());

            this.nodes.Add(device.Id, newNode);

            // Check if there's an existing parent for this device
            foreach (string parentScopeId in device.ParentScopes)
            {
                // Look for the parent based on scope ID, it's okay if we can't find a parent
                // node. It's possible that the identity for the parent hasn't came in yet.
                // In this case we'll just leave the new identity as a dangling node, and
                // the parent device identity should come in at a later point.
                Option <ServiceIdentityTreeNode> parentNode = this.FindDeviceByScopeId(parentScopeId);

                // Hook up the new node into the tree
                parentNode.ForEach(p =>
                {
                    p.AddChild(newNode);
                });
            }

            if (device.IsEdgeDevice)
            {
                // Check if there are any dangling child devices that can now be hooked up,
                // this include placing the new node as the new root.
                List <ServiceIdentityTreeNode> danglingChildren =
                    this.nodes
                    .Select(kvp => kvp.Value)
                    .Where(s => s.Identity.ParentScopes.Count() > 0 && s.Identity.ParentScopes.Contains(device.DeviceScope.OrDefault()))
                    .ToList();

                // Also check for any modules that should be parented to this new device
                danglingChildren.AddRange(this.nodes
                                          .Select(kvp => kvp.Value)
                                          .Where(s => s.Identity.IsModule && s.Identity.DeviceId == device.DeviceId)
                                          .ToList()
                                          .AsEnumerable());

                foreach (ServiceIdentityTreeNode child in danglingChildren)
                {
                    newNode.AddChild(child);
                }
            }
        }
Пример #14
0
        static void Main(string[] args)
        {
            Params ps = new Params();

            foreach (var arg in args)
            {
                if (!ps.ProcessCommandLineArgument(arg))
                {
                    usage();
                    return;
                }
            }

            if (!ps.Validate())
            {
                usage();
                return;
            }

            var serviceIdentity = ServiceIdentity.ReadFromFile(ps.ServiceFileName);

            if (serviceIdentity == null)
            {
                return;
            }

            HiResTimer.Initialize();
            if (ps.Verbose)
            {
                Console.WriteLine("Client process starting {0} threads running for {1} s...", ps.NumThreads, ps.ExperimentDuration);
            }

            Console.WriteLine("[[READY]]");

            // Start the experiment
            var threads = Client.StartThreads <Client>(ps, serviceIdentity).ToArray();

            if (ps.ExperimentDuration == 0)
            {
                threads[0].Join();
            }
            else
            {
                Thread.Sleep((int)ps.ExperimentDuration * 1000);
                Console.Out.WriteLine("[[DONE]]");
                Console.Out.Flush();
                Environment.Exit(0);
            }
        }
Пример #15
0
        /// <summary>
        /// 移除指定的标识
        /// </summary>
        /// <param name="identity"></param>
        /// <returns></returns>
        public bool Remove(ServiceIdentity identity)
        {
            ServiceIdentity item = this.Cache.Get <ServiceIdentity>(identity.Key);

            if (item != null && item.Key == identity.Key)
            {
                this.Cache.Remove(identity.Key);

                ResetIdentityKeyList();
                IdentityKeyList.Remove(identity.Key);//从全局缓存移除
                Cache.Insert <List <string> >(KeyListFlag, IdentityKeyList);
                return(true);
            }
            return(false);
        }
Пример #16
0
        /// <summary>
        /// 获取系统中的所有服务凭据
        /// </summary>
        /// <returns></returns>
        public List <ServiceIdentity> GetAllIdentitys()
        {
            List <ServiceIdentity> list    = new List <ServiceIdentity>();
            List <string>          keyList = this.IdentityKeyList;

            foreach (string key in keyList.ToArray())
            {
                ServiceIdentity item = this.Cache.Get <ServiceIdentity>(key);
                if (item != null)
                {
                    list.Add(item);
                }
            }
            return(list);
        }
Пример #17
0
        public void Add(ServiceRequest request, ServiceIdentity identity)
        {
            string key = GetKeyString(request);

            identity.Key = key;
            //插入到全局缓存
            ResetIdentityKeyList();
            IdentityKeyList.Add(key);
            Cache.Insert <List <string> >(KeyListFlag, IdentityKeyList);
            Cache.Insert <ServiceIdentity>(key, identity,
                                           new System.Runtime.Caching.CacheItemPolicy()
            {
                SlidingExpiration = identity.Expire
            });
        }
Пример #18
0
        protected LightClient(
            string remoteAddress,
            ServiceIdentity identityType = ServiceIdentity.None,
            string identityName          = null,
            string messagingPattern      = null)
        {
            if (remoteAddress.IsNullOrWhiteSpace())
            {
                throw new ArgumentException("The argument cannot be null, empty string or consist of whitespace characters only.", nameof(remoteAddress));
            }
            EndpointIdentityFactory.ValidateIdentityParameters(identityType, identityName);

            EnsureMessagingPattern(ref messagingPattern);
            BuildChannelFactory(remoteAddress, messagingPattern, EndpointIdentityFactory.CreateEndpointIdentity(identityType, identityName));
        }
Пример #19
0
        protected ContextLightClient(
            THeader context,
            string remoteAddress,
            ServiceIdentity identityType = ServiceIdentity.None,
            string identity         = null,
            string messagingPattern = null)
            : base(remoteAddress, identityType, identity, messagingPattern)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            Context = context;
        }
Пример #20
0
        public ActionResult Register(ServiceIdentity service)
        {
            try
            {
                _services.Register(service);
            }
            catch (ValidationException)
            {
            }
            catch (DuplicateRegistrationException)
            {
            }

            return(Created($"/services/{service.ServiceName}", service));
        }
Пример #21
0
        static public IEnumerable <Thread> StartExperimentThreads(Params ps, ServiceIdentity serviceIdentity)
        {
            if (ps.NumThreads < 0)
            {
                throw new ArgumentException("count is less than 1", "count");
            }

            for (int i = 0; i < ps.NumThreads; ++i)
            {
                var    c = new Client(i, ps, serviceIdentity);
                Thread t = new Thread(c.Experiment);
                t.Start();
                yield return(t);
            }
        }
Пример #22
0
        /// <summary>
        /// Updates the redirect address on the service identity with the specified value.
        /// </summary>
        /// <param name="name">The name of the service identity.</param>
        /// <param name="redirectAddress">The redirect address to set.</param>
        public void UpdateServiceIdentityRedirectAddress(string name, string redirectAddress)
        {
            ManagementService svc = CreateManagementServiceClient();

            ServiceIdentity serviceIdentity = svc.ServiceIdentities.Where(si => si.Name == name).FirstOrDefault();

            if (serviceIdentity == null)
            {
                throw new ConfigurationErrorsException("The service identity of name " + name + " could not be found.");
            }

            serviceIdentity.RedirectAddress = redirectAddress;
            svc.UpdateObject(serviceIdentity);
            svc.SaveChanges();
        }
Пример #23
0
 public RSLClient(ServiceIdentity i_serviceIdentity, string serviceName, bool i_verbose = false)
 {
     serviceIdentity = i_serviceIdentity;
     if (serviceIdentity.ServiceType != "IronRSL" + serviceName)
     {
         Console.Error.WriteLine("Provided service identity has type {0}, not IronRSL{1}.",
                                 serviceIdentity.ServiceType, serviceName);
         throw new Exception("Wrong service type");
     }
     serverPublicKeys   = serviceIdentity.Servers.Select(server => server.PublicKey).ToArray();
     verbose            = i_verbose;
     nextSeqNum         = 0;
     primaryServerIndex = 0;
     scheduler          = IoScheduler.CreateClient(serviceIdentity.Servers, verbose);
 }
Пример #24
0
        public async Task <Option <string> > GetAuthChain(string targetId)
        {
            Preconditions.CheckNonWhiteSpace(targetId, nameof(targetId));

            // Auth-chain for the acting device (when there aren't any nodes in the tree yet)
            if (targetId == this.actorDeviceId)
            {
                return(Option.Some(this.actorDeviceId));
            }
            else if (targetId == this.actorDeviceId + "/" + Constants.EdgeHubModuleId)
            {
                return(Option.Some(this.actorDeviceId + "/" + Constants.EdgeHubModuleId + ";" + this.actorDeviceId));
            }

            using (await this.nodesLock.LockAsync())
            {
                // Auth-chain for a child somewhere in the tree
                if (this.nodes.TryGetValue(targetId, out ServiceIdentityTreeNode treeNode))
                {
                    if (treeNode.AuthChain.HasValue)
                    {
                        // Check every Edge device in the authchain for disabled devices
                        string[] authChainIds = treeNode.AuthChain.Map(chain => chain.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)).OrDefault();

                        foreach (string chainId in authChainIds)
                        {
                            if (!this.nodes.TryGetValue(chainId, out ServiceIdentityTreeNode node))
                            {
                                Events.AuthChainMissingDevice(targetId, chainId);
                                return(Option.None <string>());
                            }

                            ServiceIdentity identity = node.Identity;
                            if (identity.IsEdgeDevice && identity.Status == ServiceIdentityStatus.Disabled)
                            {
                                // Chain is unuseable if one of the devices is disabled
                                Events.AuthChainDisabled(targetId, chainId);
                                return(Option.None <string>());
                            }
                        }
                    }

                    return(treeNode.AuthChain);
                }
            }

            return(Option.None <string>());
        }
Пример #25
0
        public FluentConfiguration(ServiceIdentity identity, IContainerConfiguration containerConfiguration)
        {
            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }

            if (containerConfiguration == null)
            {
                throw new ArgumentNullException("containerConfiguration");
            }

            _containerConfiguration = containerConfiguration;

            Identity = identity;
        }
Пример #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TestServiceTasksClient" /> class (creates the channel factory).
 /// </summary>
 /// <param name="remoteAddress">The remote address of the service.</param>
 /// <param name="identityType">
 /// Type of the identity: can be <see cref="ServiceIdentity.Dns" />, <see cref="ServiceIdentity.Spn" />, <see cref="ServiceIdentity.Upn" />, or
 /// <see cref="ServiceIdentity.Rsa" />.
 /// </param>
 /// <param name="identity">
 /// The identifier in the case of <see cref="ServiceIdentity.Dns" /> should be the DNS name of specified by the service's certificate or machine.
 /// If the identity type is <see cref="ServiceIdentity.Upn" /> - use the UPN of the service identity; if <see cref="ServiceIdentity.Spn" /> - use the SPN and if
 /// <see cref="ServiceIdentity.Rsa" /> - use the RSA key.
 /// </param>
 /// <param name="messagingPattern">
 /// The messaging pattern defining the configuration of the connection. If <see langword="null"/>, empty or whitespace characters only,
 /// the constructor will try to resolve the pattern from the interface's attribute <see cref="MessagingPatternAttribute"/> if present,
 /// otherwise will apply the default messaging pattern fro the transport.
 /// </param>
 public TestServiceTasksClient(
     string remoteAddress,
     ServiceIdentity identityType,
     string identity,
     string messagingPattern = null)
     : base(remoteAddress, identityType, identity, messagingPattern)
 {
     if (remoteAddress.IsNullOrWhiteSpace())
     {
         throw new ArgumentException("The argument cannot be null, empty string or consist of whitespace characters only.", nameof(remoteAddress));
     }
     if (identityType != ServiceIdentity.None && identityType != ServiceIdentity.Certificate && identity.IsNullOrWhiteSpace())
     {
         throw new ArgumentException("Invalid combination of identity parameters.");
     }
 }
        /// <summary>
        /// Update the service identity key value.
        /// </summary>
        /// <param name="name">Name of the <see cref="ServiceIdentityKey"/>.</param>
        /// <param name="keyValue">The new key value.</param>
        /// <param name="keyType">The new Key type.</param>
        public static void UpdateServiceIdentityKey(this ManagementService svc, string name, byte[] keyValue, string keyType)
        {
            ServiceIdentity serviceIdentity = svc.GetServiceIdentityByName(name);

            if (serviceIdentity != null)
            {
                foreach (ServiceIdentityKey key in serviceIdentity.ServiceIdentityKeys)
                {
                    if (key.Type == keyType)
                    {
                        key.Value = keyValue;
                        svc.UpdateObject(key);
                    }
                }
            }
        }
Пример #28
0
        protected ContextLightClient(
            THeader context,
            Binding binding,
            string remoteAddress,
            ServiceIdentity identityType,
            X509Certificate2 certificate,
            string messagingPattern = null)
            : base(binding, remoteAddress, identityType, certificate, messagingPattern)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            Context = context;
        }
        /// <summary>
        /// Serializes the object to JSON.
        /// </summary>
        /// <param name="writer">The <see cref="T: Newtonsoft.Json.JsonWriter" /> to write to.</param>
        /// <param name="obj">The object to serialize to JSON.</param>
        internal static void Serialize(JsonWriter writer, ServiceIdentity obj)
        {
            // Required properties are always serialized, optional properties are serialized when not null.
            writer.WriteStartObject();
            if (obj.Name != null)
            {
                writer.WriteProperty(obj.Name, "name", JsonWriterExtensions.WriteStringValue);
            }

            if (obj.IdentityRef != null)
            {
                writer.WriteProperty(obj.IdentityRef, "identityRef", JsonWriterExtensions.WriteStringValue);
            }

            writer.WriteEndObject();
        }
            public ResolutionResult(
                PartitionAddressInformation addresses,
                ServiceIdentity serviceIdentity)
            {
                if (addresses == null)
                {
                    throw new ArgumentNullException("addresses");
                }

                if (serviceIdentity == null)
                {
                    throw new ArgumentNullException("serviceIdentity");
                }

                this.Addresses             = addresses;
                this.TargetServiceIdentity = serviceIdentity;
            }
Пример #31
0
        public void GetAuthChain_DisabledDevice_Test()
        {
            ServiceIdentityTree tree = this.SetupTree();

            // Add another branch with a disabled Edge
            ServiceIdentity edge_L2 = CreateServiceIdentity("edge_L2", null, "edge_L2_scope", "e1_L1_scope", true, false);
            ServiceIdentity leaf    = CreateServiceIdentity("leaf", null, null, "edge_L2_scope", false);

            tree.AddOrUpdate(edge_L2).Wait();
            tree.AddOrUpdate(leaf).Wait();

            // Act
            Option <string> authChain = tree.GetAuthChain(leaf.Id).Result;

            // Assert
            Assert.False(authChain.HasValue);
        }
Пример #32
0
        public void GetAuthChain_Test()
        {
            // Setup our tree
            ServiceIdentityTree tree = this.SetupTree();

            // Check for valid auth chains
            this.CheckValidAuthChains(tree);

            // Check non-existent auth chain
            Assert.False(tree.GetAuthChain("nonexistent").Result.HasValue);

            // Insert an orphaned node and check for its invalid auth chain
            ServiceIdentity orphan = CreateServiceIdentity("orphan", null, null, null, false);

            tree.AddOrUpdate(orphan).Wait();
            Assert.False(tree.GetAuthChain(orphan.Id).Result.HasValue);
        }
Пример #33
0
        async Task HandleNewServiceIdentity(ServiceIdentity serviceIdentity)
        {
            Option <ServiceIdentity> existing = await this.serviceIdentityHierarchy.Get(serviceIdentity.Id);

            bool hasUpdated = existing.HasValue && !existing.Contains(serviceIdentity);

            await this.serviceIdentityHierarchy.InsertOrUpdate(serviceIdentity);

            await this.SaveServiceIdentityToStore(serviceIdentity.Id, new StoredServiceIdentity(serviceIdentity));

            Events.AddInScope(serviceIdentity.Id);

            if (hasUpdated)
            {
                this.ServiceIdentityUpdated?.Invoke(this, serviceIdentity);
            }
        }
 public void AddToServiceIdentities(ServiceIdentity serviceIdentity)
 {
     base.AddObject("ServiceIdentities", serviceIdentity);
 }
 public static ServiceIdentity CreateServiceIdentity(long ID, bool systemReserved)
 {
     ServiceIdentity serviceIdentity = new ServiceIdentity();
     serviceIdentity.Id = ID;
     serviceIdentity.SystemReserved = systemReserved;
     return serviceIdentity;
 }