Ejemplo n.º 1
0
        public void canCompareScopes(string greater, string lesser)
        {
            AccessScope greaterScope = AccessScope.parse(greater);
            AccessScope lesserScope  = AccessScope.parse(lesser);

            Assert.True(greaterScope.greaterThan(lesserScope));
        }
Ejemplo n.º 2
0
        public Credential?resolve(string tokenStr)
        {
            // 1. match the token string to a Token
            var token = default(Token);

            using (var db = serverContext.getDbContext()) {
                token = db.tokens.FirstOrDefault(x => x.content == tokenStr);
            }

            if (token == null)
            {
                return(null);
            }

            // 2. check token validity
            if (DateTime.Now >= token.expires)
            {
                // token is expired.
                return(null);
            }

            // 2. match the token to a user
            using (var db = serverContext.getDbContext()) {
                token = db.tokens.Find(token.id);
                db.Entry(token).Reference(x => x.user).Load();
            }

            // 3. parse token scopes/path
            return(new Credential(token, AccessScope.parse(token.scope)));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// For use only when decrypting a volume member.
        /// <para>Resets the Expired flag; useage must guarantee that the same key-to-file matching is used when re-encrypting the file.</para>
        /// </summary>
        ///
        /// <param name="KeyId">The unique subkey id</param>
        public void ResetSubKeyFlag(byte[] KeyId)
        {
            if (AccessScope.Equals(KeyScope.NoAccess))
            {
                throw new CryptoProcessingException("PackageFactory:Extract", "You do not have permission to access this key!", new UnauthorizedAccessException());
            }

            try
            {
                long keyPos;
                int  index;
                // get the key data
                MemoryStream keyStream = GetKeyStream();
                // get the keying materials starting offset within the key file
                keyPos = PackageKey.SubKeyOffset(keyStream, KeyId);

                if (keyPos == -1)
                {
                    throw new CryptoProcessingException("PackageFactory:Extract", "This package does not contain the key file!", new ArgumentException());
                }

                // get the index
                index = PackageKey.IndexFromId(keyStream, KeyId);
                PackageKey.SubKeyClearPolicy(keyStream, index, (long)PackageKeyStates.Expired);
                // write to file
                WriteKeyStream(keyStream);
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 4
0
 public Token issue(AccessScope scope, TimeSpan lifetime)
 {
     return(new Token {
         content = StringUtils.secureRandomString(TOKEN_LENGTH),
         expires = DateTime.UtcNow.Add(lifetime),
         scope = scope.path
     });
 }
Ejemplo n.º 5
0
 internal static string ToSerializedValue(this AccessScope value)
 {
     switch (value)
     {
     case AccessScope.Job:
         return("job");
     }
     return(null);
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Serves as the default hash function.
        /// </summary>
        /// <returns>A hash code for the current object.</returns>
        public override int GetHashCode()
        {
            var hashCode = 47819098;

            hashCode = (hashCode * -1521134295) + AccessScope.GetHashCode();
            hashCode = (hashCode * -1521134295) + CoherentAccess.GetHashCode();
            hashCode = (hashCode * -1521134295) + OrderedAccess.GetHashCode();
            return(hashCode);
        }
Ejemplo n.º 7
0
        public string AuthorizeUrl(string redirectUri, AccessScope scopes)
        {
            var parameters = new List <KeyValuePair <string, object> >
            {
                new KeyValuePair <string, object>("scope", scopes.ToString().ToLower().Replace(",", "")),
                new KeyValuePair <string, object>("response_type", "code"),
                new KeyValuePair <string, object>("redirect_uri", redirectUri),
                new KeyValuePair <string, object>("client_id", Client.ClientId)
            };

            return($"https://{Client.Domain}/oauth/authorize?{string.Join("&", AppClient.AsUrlParameter(parameters))}");
        }
Ejemplo n.º 8
0
        internal static AccessScope ParseScopeTag(XElement child)
        {
            var result = new AccessScope()
            {
                RId        = Convert.ToInt64(child.Value),
                ScopeType  = child.Attribute(ScopeXNames.XscopeType).Value,
                Inherit    = child.Attribute(ScopeXNames.XisInherit).Value,
                EntityType = new AccessEntity()
                {
                    Id   = Convert.ToInt32(child.Attribute(ScopeXNames.XentityTypeId).Value),
                    Name = child.Attribute(ScopeXNames.XentityTypeName).Value
                }
            };

            return(result);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Test a key to see if it contains a subkey with a specific id
        /// </summary>
        ///
        /// <param name="KeyId">The subkey id to test</param>
        ///
        /// <returns>The index of the subkey, or -1 if key is not in the PackageKey</returns>
        ///
        /// <exception cref="CryptoProcessingException">Thrown if the user has insufficient access rights to access this PackageKey</exception>
        public int ContainsSubKey(byte[] KeyId)
        {
            if (AccessScope.Equals(KeyScope.NoAccess))
            {
                throw new CryptoProcessingException("PackageFactory:ContainsSubKey", "You do not have permission to access this key!", new UnauthorizedAccessException());
            }

            for (int i = 0; i < m_keyPackage.SubKeyID.Length; i++)
            {
                if (Compare.IsEqual(KeyId, m_keyPackage.SubKeyID[i]))
                {
                    return(i);
                }
            }
            return(-1);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Test a PackageKey subkey for expired status
        /// </summary>
        ///
        /// <param name="KeyId">The subkey id to test</param>
        ///
        /// <returns>Returns true if subkey has expired and can not be used for encryption, false if a valid key</returns>
        ///
        /// <exception cref="CryptoProcessingException">Thrown if the user has insufficient access rights to access this PackageKey</exception>
        public bool HasExpired(byte[] KeyId)
        {
            if (AccessScope.Equals(KeyScope.NoAccess))
            {
                throw new CryptoProcessingException("PackageFactory:HasExpired", "You do not have permission to access this key!", new UnauthorizedAccessException());
            }

            int index = ContainsSubKey(KeyId);

            if (index < 0)
            {
                return(true);
            }

            return(PackageKey.KeyHasPolicy(m_keyPackage.SubKeyPolicy[index], (int)PackageKeyStates.Expired));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Extract the next valid subkey set (Expired flag not set) as a KeyParam, and a CipherDescription structure.
        /// <para>Used only when calling a Encryption function.</para>
        /// </summary>
        ///
        /// <param name="Description">out: The CipherDescription structure; the properties required to create a specific cipher instance</param>
        /// <param name="KeyParam">out: The KeyParams class containing a unique key, initialization vector and HMAC key</param>
        ///
        /// <returns>The KeyId array used to identify a subkey set; set as the KeyId in a MessageHeader structure</returns>
        ///
        /// <exception cref="CryptoProcessingException">Thrown if the user has insufficient access rights to perform encryption with this key.</exception>
        public byte[] NextKey(out CipherDescription Description, out KeyParams KeyParam)
        {
            if (!AccessScope.Equals(KeyScope.Creator))
            {
                throw new CryptoProcessingException("PackageFactory:NextKey", "You do not have permission to encrypt with this key!", new UnauthorizedAccessException());
            }

            try
            {
                // get the key data
                MemoryStream keyStream = GetKeyStream();
                // get the next unused key for encryption
                int index = PackageKey.NextSubkey(keyStream);

                if (index == -1)
                {
                    throw new CryptoProcessingException("PackageFactory:NextKey", "The key file has expired! There are no keys left available for encryption.", new Exception());
                }

                // get the cipher description
                Description = m_keyPackage.Description;
                // store the subkey identity, this is written into the message header to identify the subkey
                byte[] keyId = m_keyPackage.SubKeyID[index];
                // get the starting position of the keying material within the package
                long keyPos = PackageKey.SubKeyOffset(keyStream, keyId);

                // no unused keys in the package file
                if (keyPos == -1)
                {
                    throw new CryptoProcessingException("PackageFactory:NextKey", "The key file has expired! There are no keys left available for encryption.", new Exception());
                }

                // get the keying material
                KeyParam = GetKeySet(keyStream, m_keyPackage.Description, keyPos);
                // mark the subkey as expired
                PackageKey.SubKeySetPolicy(keyStream, index, (long)PackageKeyStates.Expired);
                // write to file
                WriteKeyStream(keyStream);
                // return the subkey id
                return(keyId);
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Test the PackageKey for remaining valid subkeys
        /// </summary>
        ///
        /// <returns>PackageKey contains subkeys that are valid for encryption</returns>
        ///
        /// <exception cref="CryptoProcessingException">Thrown if the user has insufficient access rights to access this PackageKey</exception>
        public bool HasExpired()
        {
            if (AccessScope.Equals(KeyScope.NoAccess))
            {
                throw new CryptoProcessingException("PackageFactory:HasExpired", "You do not have permission to access this key!", new UnauthorizedAccessException());
            }

            for (int i = 0; i < m_keyPackage.SubKeyCount; i++)
            {
                if (!PackageKey.KeyHasPolicy(m_keyPackage.SubKeyPolicy[i], (long)PackageKeyStates.Expired))
                {
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 13
0
        public async Task <(RemoteIdentity, HttpStatusCode)> getAppAuthentication(HttpRequest req, HttpResponse res)
        {
            var appId = req.RouteValues.As <string>("appId");
            // check config for app layers
            var appDef = serverContext.config.apps.SingleOrDefault(x => x.name == appId);

            if (appDef == null)
            {
                return(null, HttpStatusCode.NotFound);
            }

            // load user groups, and aggregate their permissions
            var user            = serverContext.userManager.loadGroups(currentUser);
            var userPermissions = new PermissionResolver(serverContext, user)
                                  .aggregatePermissions();
            // check if any permission grants app access
            var maybeGrantedScope = default(AccessScope?);

            foreach (var permission in userPermissions)
            {
                var permissionScope = AccessScope.parse(permission.path); // permission: "/Layer" or "/Layer/App"
                foreach (var appDefLayer in appDef.layers)
                {
                    var appScope = new AccessScope(appDefLayer, appDef.name); // scope: "/Layer/App"
                    if (permissionScope.greaterThan(appScope))
                    {
                        maybeGrantedScope = appScope; // the granted scope is the one we authorize
                    }
                }
            }

            if (!maybeGrantedScope.HasValue)
            {
                return(null, HttpStatusCode.Forbidden);
            }

            var grantedScope = maybeGrantedScope.Value;

            // issue a new token for the app
            // TODO: configurable timespan
            var token = serverContext.userManager.issueTokenFor(user.id,
                                                                serverContext.tokenResolver.issue(grantedScope, TimeSpan.FromDays(7)));

            return(new RemoteIdentity(new PublicUser(user), token), HttpStatusCode.Created);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Get information about the key file in the form of an <see cref="PackageInfo"/> structure
        /// </summary>
        ///
        /// <returns>A <see cref="PackageInfo"/> structure</returns>
        ///
        /// <exception cref="CryptoProcessingException">Thrown if the user has insufficient access rights to access this PackageKey</exception>
        public PackageInfo KeyInfo()
        {
            if (AccessScope.Equals(KeyScope.NoAccess))
            {
                throw new CryptoProcessingException("PackageFactory:KeyInfo", "You do not have permission to access this key!", new UnauthorizedAccessException());
            }

            PackageInfo info = new PackageInfo(m_keyPackage);

            // return limited data
            if (PackageKey.KeyHasPolicy(KeyPolicy, (long)KeyPolicies.NoNarrative))
            {
                info.Origin = Guid.Empty;
                info.Policies.Clear();
            }

            return(info);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// For use only when decrypting a volume member.
        /// <para>Resets the Expired flag; useage must guarantee that the same key-to-file matching is used when re-encrypting the file.</para>
        /// </summary>
        ///
        /// <param name="Index">The subkey index</param>
        public void ResetSubKeyFlag(int Index)
        {
            if (AccessScope.Equals(KeyScope.NoAccess))
            {
                throw new CryptoProcessingException("PackageFactory:Extract", "You do not have permission to access this key!", new UnauthorizedAccessException());
            }

            try
            {
                // get the key data
                MemoryStream keyStream = GetKeyStream();
                PackageKey.SubKeyClearPolicy(keyStream, Index, (long)PackageKeyStates.Expired);
                // write to file
                WriteKeyStream(keyStream);
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Get the policy flags for a subkey
        /// </summary>
        ///
        /// <param name="KeyId">Id of the subkey to query</param>
        ///
        /// <returns>Sub key policy flag, or -1 if not key id found</returns>
        ///
        /// <exception cref="CryptoProcessingException">Thrown if the user has insufficient access rights to access this PackageKey</exception>
        public long Policy(byte[] KeyId)
        {
            if (AccessScope.Equals(KeyScope.NoAccess))
            {
                throw new CryptoProcessingException("PackageFactory:Policy", "You do not have permission to access this key!", new UnauthorizedAccessException());
            }

            int index = ContainsSubKey(KeyId);

            if (index < 0)
            {
                return(-1);
            }

            if (index > m_keyPackage.SubKeyPolicy.Length)
            {
                return(-1);
            }

            return(m_keyPackage.SubKeyPolicy[index]);
        }
Ejemplo n.º 17
0
        protected AuthenticatedModule(AccessScope minimumScope, User.Role minimumRole, string path,
                                      SContext serverContext) : base(path, serverContext)
        {
            // require authentication
            this.requiresUserAuthentication();

            this.Before += async(ctx) => {
                var usernameClaim = ctx.User.Claims.First(x => x.Type == IBearerAuthenticator.CLAIM_USERNAME);
                currentUser = serverContext.userManager.findByUsername(usernameClaim.Value);

                if (currentUser.role < minimumRole)
                {
                    // give a special code for pending users
                    if (currentUser.role == User.Role.Pending)
                    {
                        ctx.Response.StatusCode = (int)HttpStatusCode.Locked;
                    }
                    else
                    {
                        ctx.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    }

                    return(false);
                }

                var tokenClaim = ctx.User.Claims.First(x => x.Type == IBearerAuthenticator.CLAIM_TOKEN);
                credential = serverContext.tokenResolver.resolve(tokenClaim.Value).Value;

                // check if at least minimum scope
                if (!credential.scope.greaterThan(minimumScope))
                {
                    ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(false);
                }

                return(true);
            };
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Extract a subkey set (KeyParam), a file extension key, and a CipherDescription.
        /// <para>Used only when calling a Decryption function to get a specific subkey
        /// The KeyId field corresponds with the KeyId field contained in a MessageHeader structure.</para>
        /// </summary>
        ///
        /// <param name="KeyId">The KeyId array used to identify a subkey set; set as the KeyId in a MessageHeader structure</param>
        /// <param name="Description">out: The CipherDescription structure; the properties required to create a specific cipher instance</param>
        /// <param name="KeyParam">out: The KeyParams class containing a unique key, initialization vector and HMAC key</param>
        ///
        /// <exception cref="CryptoProcessingException">Thrown if the user has insufficient access rights to access this PackageKey, or the PackageKey does not contain the KeyId specified</exception>
        public void Extract(byte[] KeyId, out CipherDescription Description, out KeyParams KeyParam)
        {
            if (AccessScope.Equals(KeyScope.NoAccess))
            {
                throw new CryptoProcessingException("PackageFactory:Extract", "You do not have permission to access this key!", new UnauthorizedAccessException());
            }

            try
            {
                long keyPos;
                int  index;
                // get the key data
                MemoryStream keyStream = GetKeyStream();
                // get the keying materials starting offset within the key file
                keyPos = PackageKey.SubKeyOffset(keyStream, KeyId);

                if (keyPos == -1)
                {
                    throw new CryptoProcessingException("PackageFactory:Extract", "This package does not contain the key file!", new ArgumentException());
                }

                // get the index
                index = PackageKey.IndexFromId(keyStream, KeyId);
                // key flagged SingleUse was used for decryption and is locked out
                if (PackageKey.KeyHasPolicy(m_keyPackage.SubKeyPolicy[index], (long)PackageKeyStates.Locked) && !PackageKey.KeyHasPolicy(KeyPolicy, (long)KeyPolicies.VolumeKey))
                {
                    throw new CryptoProcessingException("PackageFactory:Extract", "SubKey is locked. The subkey has a single use policy and was previously used to decrypt the file.", new Exception());
                }
                // key flagged PostOverwrite was used for decryption and was erased
                if (PackageKey.KeyHasPolicy(m_keyPackage.SubKeyPolicy[index], (long)PackageKeyStates.Erased))
                {
                    throw new CryptoProcessingException("PackageFactory:Extract", "SubKey is erased. The subkey has a post erase policy and was previously used to decrypt the file.", new Exception());
                }

                // get the cipher description
                Description = m_keyPackage.Description;
                // get the keying material
                KeyParam = GetKeySet(keyStream, m_keyPackage.Description, keyPos);

                // test flags for overwrite or single use policies
                if (PackageKey.KeyHasPolicy(KeyPolicy, (long)KeyPolicies.PostOverwrite))
                {
                    PackageKey.SubKeySetPolicy(keyStream, index, (long)PackageKeyStates.Erased);
                }
                else if (PackageKey.KeyHasPolicy(KeyPolicy, (long)KeyPolicies.SingleUse))
                {
                    PackageKey.SubKeySetPolicy(keyStream, index, (long)PackageKeyStates.Locked);
                }

                // post overwrite flag set, erase the subkey
                if (PackageKey.KeyHasPolicy(KeyPolicy, (long)KeyPolicies.PostOverwrite))
                {
                    int keySize = Description.KeySize + Description.IvSize + Description.MacKeySize;
                    // overwrite the region within file
                    Erase(keyStream, keyPos, keySize);
                    // clear this section of the key
                    keyStream.Seek(keyPos, SeekOrigin.Begin);
                    keyStream.Write(new byte[keySize], 0, keySize);
                }

                // write to file
                WriteKeyStream(keyStream);
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 19
0
        private BWebServiceResponse UpdateBaseRightForUser(HttpListenerContext _Context, Action <string> _ErrorMessageAction)
        {
            var NewRights = new List <string>();

            using (var InputStream = _Context.Request.InputStream)
            {
                using (var ResponseReader = new StreamReader(InputStream))
                {
                    try
                    {
                        var NewRightsArray = JArray.Parse(ResponseReader.ReadToEnd());
                        foreach (string NewRight in NewRightsArray)
                        {
                            var NewRightCaseCorrected = NewRight.ToUpper();
                            if (AccessScopeLibrary.ACCESS_RIGHTS.Contains(NewRightCaseCorrected))
                            {
                                NewRights.Add(NewRightCaseCorrected);
                            }
                        }
                        NewRights = NewRights.Distinct().ToList();
                        NewRights.Sort();
                    }
                    catch (Exception e)
                    {
                        _ErrorMessageAction?.Invoke("User_UpdateDeleteBaseRight_ForUser->UpdateBaseRightForUser: Read request body stage has failed. Exception: " + e.Message + ", Trace: " + e.StackTrace);
                        return(BWebResponse.BadRequest("Malformed request body. Request must be a valid json form."));
                    }
                }
            }

            if (NewRights.Count == 0)
            {
                return(BWebResponse.BadRequest("Request does not contain any valid access right. Use DELETE method for deleting the scope. Access rights can be: " + AccessScopeLibrary.GetPossibleAccessRightsText()));
            }

            var UserKey = new BPrimitiveType(RequestedUserID);

            if (!DatabaseService.GetItem(
                    UserDBEntry.DBSERVICE_USERS_TABLE(),
                    UserDBEntry.KEY_NAME_USER_ID,
                    UserKey,
                    UserDBEntry.Properties,
                    out JObject UserObject,
                    _ErrorMessageAction))
            {
                return(BWebResponse.InternalError("Database fetch-user-info operation has failed."));
            }
            if (UserObject == null)
            {
                return(BWebResponse.NotFound("User does not exist."));
            }

            if (!UserObject.ContainsKey(UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY))
            {
                return(BWebResponse.NotFound("User does not have any base rights."));
            }

            var BaseAccessScopeAsArray = (JArray)UserObject[UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY];
            var BaseAccessScopeAsList  = new List <AccessScope>();

            //Check existence of access scope
            AccessScope ExistingAccessScope      = null;
            int         ExistingAccessScopeIndex = -1;

            int j = 0;

            foreach (JObject BaseAccessScopeObject in BaseAccessScopeAsArray)
            {
                var Scope = JsonConvert.DeserializeObject <AccessScope>(BaseAccessScopeObject.ToString());
                BaseAccessScopeAsList.Add(Scope);

                if (ExistingAccessScopeIndex == -1 && Scope.WildcardPath == RequestedBaseRightWildcard)
                {
                    ExistingAccessScope      = Scope;
                    ExistingAccessScopeIndex = j;
                }
                j++;
            }

            if (ExistingAccessScopeIndex == -1)
            {
                return(BWebResponse.NotFound("User does not have the given base right."));
            }

            ExistingAccessScope.AccessRights.Sort();

            //Check if requested rights are different
            bool bDifferent = false;

            if (ExistingAccessScope.AccessRights.Count == NewRights.Count)
            {
                for (var i = 0; i < ExistingAccessScope.AccessRights.Count; i++)
                {
                    if (ExistingAccessScope.AccessRights[i] != NewRights[i])
                    {
                        bDifferent = true;
                        break;
                    }
                }
            }
            else
            {
                bDifferent = true;
            }

            if (bDifferent)
            {
                ExistingAccessScope.AccessRights = NewRights;
                BaseAccessScopeAsArray[ExistingAccessScopeIndex] = JObject.Parse(JsonConvert.SerializeObject(ExistingAccessScope));

                UserObject[UserDBEntry.BASE_ACCESS_SCOPE_PROPERTY] = BaseAccessScopeAsArray;

                Controller_DeliveryEnsurer.Get().DB_UpdateItem_FireAndForget(
                    _Context,
                    UserDBEntry.DBSERVICE_USERS_TABLE(),
                    UserDBEntry.KEY_NAME_USER_ID,
                    UserKey,
                    UserObject);

                MemoryService.SetKeyValue(CommonData.MemoryQueryParameters, new Tuple <string, BPrimitiveType>[]
                {
                    new Tuple <string, BPrimitiveType>(
                        UserBaseAccessMEntry.M_KEY_NAME_USER_ID + RequestedUserID,
                        new BPrimitiveType(JsonConvert.SerializeObject(new UserBaseAccessMEntry()
                    {
                        BaseAccessScope = BaseAccessScopeAsList
                    })))
                }, _ErrorMessageAction);
            }

            return(BWebResponse.StatusOK("Base right has been updated."));
        }
Ejemplo n.º 20
0
 public bool Equals(TokenKey other) =>
 other != null &&
 this.CharacterId == other.CharacterId &&
 AccessScope.SequenceEqual(other.AccessScope);
Ejemplo n.º 21
0
        public async Task <Application> RegisterAsync(string clientName, string redirectUris, AccessScope scopes, string website = null)
        {
            var parameters = new List <KeyValuePair <string, object> >
            {
                new KeyValuePair <string, object>("client_name", clientName),
                new KeyValuePair <string, object>("redirect_uris", redirectUris),
                new KeyValuePair <string, object>("scopes", scopes.ToString().ToLower().Replace(",", ""))
            };

            parameters.AddIfValidValue("website", website);

            var response = await PostAsync <Application>(parameters : parameters).Stay();

            Client.ClientId     = response.ClientId;
            Client.ClientSecret = response.ClientSecret;

            return(response);
        }
        public PropertyUnitTests(ITestOutputHelper testOutputHelper)
        {
            this.testOutputHelper = testOutputHelper;

            //Define the factories
            this.defaultObjectFactory = new ObjectFactory();

            this.proxyPropertyToObjectModelMapping = new List <ComparerPropertyMapping>()
            {
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "AutoScaleEnabled", "EnableAutoScale"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "VirtualMachineSize", "VmSize"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "MaxTasksPerComputeNode", "MaxTasksPerNode"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "Statistics", "Stats"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "InterComputeNodeCommunicationEnabled", "EnableInterNodeCommunication"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "CurrentDedicatedComputeNodes", "CurrentDedicatedNodes"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "CurrentLowPriorityComputeNodes", "CurrentLowPriorityNodes"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "TargetDedicatedComputeNodes", "TargetDedicatedNodes"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "TargetLowPriorityComputeNodes", "TargetLowPriorityNodes"),

                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "VirtualMachineSize", "VmSize"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "AutoScaleEnabled", "EnableAutoScale"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "MaxTasksPerComputeNode", "MaxTasksPerNode"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "InterComputeNodeCommunicationEnabled", "EnableInterNodeCommunication"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "TargetDedicatedComputeNodes", "TargetDedicatedNodes"),
                new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "TargetLowPriorityComputeNodes", "TargetLowPriorityNodes"),

                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "AutoScaleEnabled", "EnableAutoScale"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "VirtualMachineSize", "VmSize"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "MaxTasksPerComputeNode", "MaxTasksPerNode"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "InterComputeNodeCommunicationEnabled", "EnableInterNodeCommunication"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "CurrentDedicatedComputeNodes", "CurrentDedicatedNodes"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "CurrentLowPriorityComputeNodes", "CurrentLowPriorityNodes"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "TargetDedicatedComputeNodes", "TargetDedicatedNodes"),
                new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "TargetLowPriorityComputeNodes", "TargetLowPriorityNodes"),

                new ComparerPropertyMapping(typeof(CloudServiceConfiguration), typeof(Protocol.Models.CloudServiceConfiguration), "OSFamily", "OsFamily"),
                new ComparerPropertyMapping(typeof(CloudServiceConfiguration), typeof(Protocol.Models.CloudServiceConfiguration), "OSVersion", "OsVersion"),

                new ComparerPropertyMapping(typeof(TaskInformation), typeof(Protocol.Models.TaskInformation), "ExecutionInformation", "TaskExecutionInformation"),

                new ComparerPropertyMapping(typeof(AutoPoolSpecification), typeof(Protocol.Models.AutoPoolSpecification), "PoolSpecification", "Pool"),

                new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "ComputeNodeId", "NodeId"),
                new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "ComputeNodeUrl", "NodeUrl"),
                new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "JobPreparationTaskExecutionInformation", "JobPreparationTaskExecutionInfo"),
                new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "JobReleaseTaskExecutionInformation", "JobReleaseTaskExecutionInfo"),

                new ComparerPropertyMapping(typeof(JobPreparationTaskExecutionInformation), typeof(Protocol.Models.JobPreparationTaskExecutionInformation), "FailureInformation", "FailureInfo"),
                new ComparerPropertyMapping(typeof(JobPreparationTaskExecutionInformation), typeof(Protocol.Models.JobPreparationTaskExecutionInformation), "ContainerInformation", "ContainerInfo"),

                new ComparerPropertyMapping(typeof(JobReleaseTaskExecutionInformation), typeof(Protocol.Models.JobReleaseTaskExecutionInformation), "FailureInformation", "FailureInfo"),
                new ComparerPropertyMapping(typeof(JobReleaseTaskExecutionInformation), typeof(Protocol.Models.JobReleaseTaskExecutionInformation), "ContainerInformation", "ContainerInfo"),

                new ComparerPropertyMapping(typeof(TaskExecutionInformation), typeof(Protocol.Models.TaskExecutionInformation), "FailureInformation", "FailureInfo"),
                new ComparerPropertyMapping(typeof(TaskExecutionInformation), typeof(Protocol.Models.TaskExecutionInformation), "ContainerInformation", "ContainerInfo"),

                new ComparerPropertyMapping(typeof(SubtaskInformation), typeof(Protocol.Models.SubtaskInformation), "FailureInformation", "FailureInfo"),
                new ComparerPropertyMapping(typeof(SubtaskInformation), typeof(Protocol.Models.SubtaskInformation), "ContainerInformation", "ContainerInfo"),

                new ComparerPropertyMapping(typeof(StartTaskInformation), typeof(Protocol.Models.StartTaskInformation), "FailureInformation", "FailureInfo"),
                new ComparerPropertyMapping(typeof(StartTaskInformation), typeof(Protocol.Models.StartTaskInformation), "ContainerInformation", "ContainerInfo"),

                new ComparerPropertyMapping(typeof(PoolStatistics), typeof(Protocol.Models.PoolStatistics), "UsageStatistics", "UsageStats"),
                new ComparerPropertyMapping(typeof(PoolStatistics), typeof(Protocol.Models.PoolStatistics), "ResourceStatistics", "ResourceStats"),

                new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "UserCpuTime", "UserCPUTime"),
                new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "KernelCpuTime", "KernelCPUTime"),
                new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "SucceededTaskCount", "NumSucceededTasks"),
                new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "FailedTaskCount", "NumFailedTasks"),
                new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "TaskRetryCount", "NumTaskRetries"),

                new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "UserCpuTime", "UserCPUTime"),
                new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "KernelCpuTime", "KernelCPUTime"),
                new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "SucceededTaskCount", "NumSucceededTasks"),
                new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "FailedTaskCount", "NumFailedTasks"),
                new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "TaskRetryCount", "NumTaskRetries"),

                new ComparerPropertyMapping(typeof(ResourceStatistics), typeof(Protocol.Models.ResourceStatistics), "AverageCpuPercentage", "AvgCPUPercentage"),
                new ComparerPropertyMapping(typeof(ResourceStatistics), typeof(Protocol.Models.ResourceStatistics), "AverageMemoryGiB", "AvgMemoryGiB"),
                new ComparerPropertyMapping(typeof(ResourceStatistics), typeof(Protocol.Models.ResourceStatistics), "AverageDiskGiB", "AvgDiskGiB"),

                new ComparerPropertyMapping(typeof(TaskStatistics), typeof(Protocol.Models.TaskStatistics), "UserCpuTime", "UserCPUTime"),
                new ComparerPropertyMapping(typeof(TaskStatistics), typeof(Protocol.Models.TaskStatistics), "KernelCpuTime", "KernelCPUTime"),

                new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.CloudJob), "PoolInformation", "PoolInfo"),
                new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.CloudJob), "ExecutionInformation", "ExecutionInfo"),
                new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.CloudJob), "Statistics", "Stats"),

                new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.JobAddParameter), "PoolInformation", "PoolInfo"),

                new ComparerPropertyMapping(typeof(JobSpecification), typeof(Protocol.Models.JobSpecification), "PoolInformation", "PoolInfo"),

                new ComparerPropertyMapping(typeof(CloudJobSchedule), typeof(Protocol.Models.CloudJobSchedule), "ExecutionInformation", "ExecutionInfo"),
                new ComparerPropertyMapping(typeof(CloudJobSchedule), typeof(Protocol.Models.CloudJobSchedule), "Statistics", "Stats"),

                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "AffinityInformation", "AffinityInfo"),
                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "ExecutionInformation", "ExecutionInfo"),
                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "ComputeNodeInformation", "NodeInfo"),
                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "Statistics", "Stats"),

                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.TaskAddParameter), "AffinityInformation", "AffinityInfo"),
                new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.TaskAddParameter), "ComputeNodeInformation", "NodeInfo"),

                new ComparerPropertyMapping(typeof(ExitConditions), typeof(Protocol.Models.ExitConditions), "Default", "DefaultProperty"),

                new ComparerPropertyMapping(typeof(TaskInformation), typeof(Protocol.Models.TaskInformation), "ExecutionInformation", "ExecutionInfo"),

                new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "IPAddress", "IpAddress"),
                new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "VirtualMachineSize", "VmSize"),
                new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "StartTaskInformation", "StartTaskInfo"),
                new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "NodeAgentInformation", "NodeAgentInfo"),

                new ComparerPropertyMapping(typeof(ComputeNodeInformation), typeof(Protocol.Models.ComputeNodeInformation), "ComputeNodeId", "NodeId"),
                new ComparerPropertyMapping(typeof(ComputeNodeInformation), typeof(Protocol.Models.ComputeNodeInformation), "ComputeNodeUrl", "NodeUrl"),

                new ComparerPropertyMapping(typeof(JobPreparationTask), typeof(Protocol.Models.JobPreparationTask), "RerunOnComputeNodeRebootAfterSuccess", "RerunOnNodeRebootAfterSuccess"),

                new ComparerPropertyMapping(typeof(ImageReference), typeof(Protocol.Models.ImageReference), "SkuId", "Sku"),

                new ComparerPropertyMapping(typeof(VirtualMachineConfiguration), typeof(Protocol.Models.VirtualMachineConfiguration), "NodeAgentSkuId", "NodeAgentSKUId"),
                new ComparerPropertyMapping(typeof(VirtualMachineConfiguration), typeof(Protocol.Models.VirtualMachineConfiguration), "OSDisk", "OsDisk"),

                new ComparerPropertyMapping(typeof(TaskSchedulingPolicy), typeof(Protocol.Models.TaskSchedulingPolicy), "ComputeNodeFillType", "NodeFillType"),

                new ComparerPropertyMapping(typeof(PoolEndpointConfiguration), typeof(Protocol.Models.PoolEndpointConfiguration), "InboundNatPools", "InboundNATPools"),
                new ComparerPropertyMapping(typeof(InboundEndpoint), typeof(Protocol.Models.InboundEndpoint), "PublicFqdn", "PublicFQDN"),

                new ComparerPropertyMapping(typeof(ImageInformation), typeof(Protocol.Models.ImageInformation), "NodeAgentSkuId", "NodeAgentSKUId"),
                new ComparerPropertyMapping(typeof(ImageInformation), typeof(Protocol.Models.ImageInformation), "OSType", "OsType"),
            };

            Random rand = new Random();

            Func <object> omTaskRangeBuilder = () =>
            {
                int rangeLimit1 = rand.Next(0, int.MaxValue);
                int rangeLimit2 = rand.Next(0, int.MaxValue);

                return(new TaskIdRange(Math.Min(rangeLimit1, rangeLimit2), Math.Max(rangeLimit1, rangeLimit2)));
            };

            Func <object> iFileStagingProviderBuilder = () => null;

            Func <object> batchClientBehaviorBuilder = () => null;

            Func <object> taskRangeBuilder = () =>
            {
                int rangeLimit1 = rand.Next(0, int.MaxValue);
                int rangeLimit2 = rand.Next(0, int.MaxValue);

                return(new Protocol.Models.TaskIdRange(Math.Min(rangeLimit1, rangeLimit2), Math.Max(rangeLimit1, rangeLimit2)));
            };

            ObjectFactoryConstructionSpecification certificateReferenceSpecification = new ObjectFactoryConstructionSpecification(
                typeof(Protocol.Models.CertificateReference),
                () => BuildCertificateReference(rand));

            ObjectFactoryConstructionSpecification authenticationTokenSettingsSpecification = new ObjectFactoryConstructionSpecification(
                typeof(Protocol.Models.AuthenticationTokenSettings),
                () => BuildAuthenticationTokenSettings(rand));

            ObjectFactoryConstructionSpecification taskRangeSpecification = new ObjectFactoryConstructionSpecification(
                typeof(Protocol.Models.TaskIdRange),
                taskRangeBuilder);

            ObjectFactoryConstructionSpecification omTaskRangeSpecification = new ObjectFactoryConstructionSpecification(
                typeof(TaskIdRange),
                omTaskRangeBuilder);

            ObjectFactoryConstructionSpecification batchClientBehaviorSpecification = new ObjectFactoryConstructionSpecification(
                typeof(BatchClientBehavior),
                batchClientBehaviorBuilder);

            ObjectFactoryConstructionSpecification fileStagingProviderSpecification = new ObjectFactoryConstructionSpecification(
                typeof(IFileStagingProvider),
                iFileStagingProviderBuilder);

            this.customizedObjectFactory = new ObjectFactory(new List <ObjectFactoryConstructionSpecification>
            {
                certificateReferenceSpecification,
                authenticationTokenSettingsSpecification,
                taskRangeSpecification,
                omTaskRangeSpecification,
                fileStagingProviderSpecification,
                batchClientBehaviorSpecification,
            });

            // We need a custom comparison rule for certificate references because they are a different type in the proxy vs
            // the object model (string in proxy, flags enum in OM
            ComparisonRule certificateReferenceComparisonRule = ComparisonRule.Create <CertificateVisibility?, List <Protocol.Models.CertificateVisibility> >(
                typeof(CertificateReference),
                typeof(Protocol.Models.CertificateReference), // This is the type that hold the target property
                (visibility, proxyVisibility) =>
            {
                CertificateVisibility?convertedProxyVisibility = UtilitiesInternal.ParseCertificateVisibility(proxyVisibility);

                //Treat null as None for the purposes of comparison:
                bool areEqual = convertedProxyVisibility == visibility || !visibility.HasValue && convertedProxyVisibility == CertificateVisibility.None;

                return(areEqual ? ObjectComparer.CheckEqualityResult.True : ObjectComparer.CheckEqualityResult.False("Certificate visibility doesn't match"));
            },
                type1PropertyName: "Visibility",
                type2PropertyName: "Visibility");

            ComparisonRule accessScopeComparisonRule = ComparisonRule.Create <AccessScope, List <Protocol.Models.AccessScope> >(
                typeof(AuthenticationTokenSettings),
                typeof(Protocol.Models.AuthenticationTokenSettings),  // This is the type that hold the target property
                (scope, proxyVisibility) =>
            {
                AccessScope convertedProxyAccessScope = UtilitiesInternal.ParseAccessScope(proxyVisibility);

                //Treat null as None for the purposes of comparison:
                bool areEqual = convertedProxyAccessScope == scope || convertedProxyAccessScope == AccessScope.None;

                return(areEqual ? ObjectComparer.CheckEqualityResult.True : ObjectComparer.CheckEqualityResult.False("AccessScope doesn't match"));
            },
                type1PropertyName: "Access",
                type2PropertyName: "Access");

            this.objectComparer = new ObjectComparer(
                comparisonRules: new List <ComparisonRule>()
            {
                certificateReferenceComparisonRule, accessScopeComparisonRule
            },
                propertyMappings: this.proxyPropertyToObjectModelMapping,
                shouldThrowOnPropertyReadException: e => !(e.InnerException is InvalidOperationException) || !e.InnerException.Message.Contains("while the object is in the Unbound"));
        }
Ejemplo n.º 23
0
 public void canParseScopesFromPath(string path)
 {
     // ensure parsed path matches input path
     Assert.Equal(path, AccessScope.parse(path).path);
 }
Ejemplo n.º 24
0
 public Credential(Token token, AccessScope scope)
 {
     this.token = token;
     this.scope = scope;
 }