Ejemplo n.º 1
0
        public void DeserializeString()
        {
            string bleh = "hi2u";

            using (MemoryStream ms = new MemoryStream())
            {
                Serializer.Serialize <string>(ms, bleh);
                var result = ms.ToArray();
                var final  = SerializerExtensions.Deserialize <string>(result);
                Assert.AreEqual(final, bleh);
            }
        }
Ejemplo n.º 2
0
        public UsersModule()
            : base("/users")
        {
            // Generates a random series of user identifiers, returning them to the user.
            Post["/"] = parameters =>
            {
                UserIdentifier user = SerializerExtensions.Deserialize <UserIdentifier>(this.Context);

                Global.EmailManager.ValidateUserEmail(user.Email);
                UserSecret secret = AssignSecretsAndSendVerificationEmail(user);
                Global.NapackStorageManager.AddUser(user);

                logger.Info($"Assigned user {user.Email} a hash and secrets, and attempted to send a validation email.");
                return(this.Response.AsJson(new Common.UserSecret()
                {
                    UserId = user.Email,
                    Secrets = secret.Secrets
                }));
            };

            // Confirms a user's registration.
            Patch["/"] = parameters =>
            {
                UserIdentifier user = SerializerExtensions.Deserialize <UserIdentifier>(this.Context);
                Global.EmailManager.ValidateUserEmail(user.Email);

                UserIdentifier serverSideUser = Global.NapackStorageManager.GetUser(user.Email);
                if (!serverSideUser.EmailConfirmed && user.EmailVerificationCode == serverSideUser.EmailVerificationCode)
                {
                    serverSideUser.EmailConfirmed = true;
                }

                Global.NapackStorageManager.UpdateUser(serverSideUser);

                return(this.Response.AsJson(new
                {
                    UserId = user.Email,
                    EmailValidated = serverSideUser.EmailConfirmed
                }));
            };

            Delete["/"] = parameters =>
            {
                UserIdentifier user = SerializerExtensions.Deserialize <UserIdentifier>(this.Context);
                UserIdentifier.VerifyAuthorization(this.Request.Headers.ToDictionary(hdr => hdr.Key, hdr => hdr.Value), Global.NapackStorageManager, new List <string> {
                    user.Email
                });
                return(DeleteUser(this.Response, user));
            };
        }
Ejemplo n.º 3
0
        public void SerializeAndDeserializeComplexObject()
        {
            var test = new TestObject()
            {
                MyInt    = 10,
                MyString = "Test"
            };

            var serialized   = test.ToBinaryArray();
            var deserialized = SerializerExtensions.Deserialize <TestObject>(serialized);

            Assert.AreEqual(deserialized.MyInt, test.MyInt);
            Assert.AreEqual(deserialized.MyString, test.MyString);
        }
Ejemplo n.º 4
0
        public void SerializeAndDeserializeList()
        {
            List <string> strings = new List <string>();

            strings.Add("test");
            strings.Add("test2");
            strings.Add("test3");

            var serialized   = strings.ToBinaryArray();
            var deserialized = SerializerExtensions.Deserialize <List <string> >(serialized);

            Assert.AreEqual(deserialized[0], "test");
            Assert.AreEqual(deserialized[1], "test2");
            Assert.AreEqual(deserialized[2], "test3");
        }
Ejemplo n.º 5
0
        public void SerializeAndDeserializeListComplexObject()
        {
            List <TestObject> test = new List <TestObject>();

            for (int x = 0; x < 100; ++x)
            {
                test.Add(new TestObject()
                {
                    MyString = "string" + x.ToString(),
                    MyInt    = x
                });
            }

            var serialized   = test.ToBinaryArray();
            var deserialized = SerializerExtensions.Deserialize <List <TestObject> >(serialized);

            Assert.AreEqual(test.Count, 100);
            Assert.AreEqual(test[10].MyString, "string10");
            Assert.AreEqual(test[50], 50);
        }
Ejemplo n.º 6
0
        public AdminModule()
            : base("/admin")
        {
            // Shuts down the Napack Framework Server cleanly.
            Post["/shutdown"] = parameters =>
            {
                AdminModule.ValidateAdmin(this.Context);
                Global.ShutdownEvent.Set();
                return(this.Response.AsJson(new { UtcTime = DateTime.UtcNow }, HttpStatusCode.ImATeapot));
            };

            // Performs the specified user modification to the given user.
            Patch["/users"] = parameters =>
            {
                UserModification userModification = SerializerExtensions.Deserialize <UserModification>(this.Context);
                AdminModule.ValidateAdmin(this.Context);

                UserIdentifier user = Global.NapackStorageManager.GetUser(userModification.UserId);
                switch (userModification.Operation)
                {
                case Operation.DeleteUser:
                    return(UsersModule.DeleteUser(this.Response, user));

                case Operation.UpdateAccessKeys:
                    UsersModule.AssignSecretsAndSendVerificationEmail(user);
                    Global.NapackStorageManager.UpdateUser(user);
                    break;
                }

                return(this.Response.AsJson(new
                {
                    OperationPerformed = userModification.Operation
                }));
            };

            // Recalls a package.
            Post["/recall/{packageName}/{majorVersion}"] = parameters =>
            {
                string packageName  = parameters.packageName;
                int    majorVersion = int.Parse(parameters.majorVersion);
                AdminModule.ValidateAdmin(this.Context);

                NapackMetadata             metadata             = Global.NapackStorageManager.GetPackageMetadata(packageName, true);
                NapackMajorVersionMetadata majorVersionMetadata = metadata.GetMajorVersion(majorVersion);
                majorVersionMetadata.Recalled = true;
                Global.NapackStorageManager.UpdatePackageMetadata(metadata);

                return(this.Response.AsJson(new
                {
                    VersionRecalled = majorVersion
                }));
            };

            // Deletes a package.
            //
            // Deleting a Napack involves removing:
            // - The package statistics.
            // - All of the specs.
            // - All of the packages.
            // - The metadata

            // In addition, the package is removed from.
            // - The listing of packages an author has authored.
            // - The listing of packages a user has access to.
            // - Each package that took a dependency on this package*
            //
            // Finally, an email is sent to all affected users and authorized users.
            Delete["/manage/{packageName}"] = parameters =>
            {
                string packageName = parameters.packageName;
                AdminModule.ValidateAdmin(this.Context);

                // TODO there's a lot of hardening that can be done here to prevent failures.
                NapackMetadata metadata = Global.NapackStorageManager.GetPackageMetadata(packageName, true);
                Global.NapackStorageManager.RemovePackageStatistics(packageName);

                foreach (string authorizedUser in metadata.AuthorizedUserIds)
                {
                    Global.NapackStorageManager.RemoveAuthoredPackages(authorizedUser, packageName);
                }

                Dictionary <string, List <NapackVersionIdentifier> > packagesToRemovePerAuthor = new Dictionary <string, List <NapackVersionIdentifier> >();
                foreach (KeyValuePair <int, NapackMajorVersionMetadata> majorVersion in metadata.Versions)
                {
                    foreach (KeyValuePair <int, List <int> > minorVersion in majorVersion.Value.Versions)
                    {
                        foreach (int patchVersion in minorVersion.Value)
                        {
                            NapackVersionIdentifier versionIdentifier = new NapackVersionIdentifier(packageName, majorVersion.Key, minorVersion.Key, patchVersion);
                            NapackVersion           version           = Global.NapackStorageManager.GetPackageVersion(versionIdentifier);

                            foreach (string author in version.Authors)
                            {
                                if (!packagesToRemovePerAuthor.ContainsKey(author))
                                {
                                    packagesToRemovePerAuthor.Add(author, new List <NapackVersionIdentifier>());
                                }

                                packagesToRemovePerAuthor[author].Add(versionIdentifier);
                            }

                            Global.NapackStorageManager.RemovePackageVersion(versionIdentifier);
                            Global.NapackStorageManager.RemovePackageSpecification(versionIdentifier);
                        }
                    }
                }

                HashSet <string> affectedPackages = new HashSet <string>();
                foreach (NapackMajorVersion majorVersion in metadata.Versions.Keys.Select(value => new NapackMajorVersion(packageName, value)))
                {
                    List <NapackVersionIdentifier> consumingPackages = Global.NapackStorageManager.GetPackageConsumers(majorVersion).ToList();
                    foreach (NapackVersionIdentifier consumingPackage in consumingPackages)
                    {
                        NapackVersion version = Global.NapackStorageManager.GetPackageVersion(consumingPackage);
                        if (version.Dependencies.Remove(majorVersion))
                        {
                            Global.NapackStorageManager.UpdatePackageVersion(consumingPackage, version);
                            affectedPackages.Add(consumingPackage.NapackName);
                        }
                    }
                }

                HashSet <string> affectedUsers = new HashSet <string>();
                foreach (string affectedPackage in affectedPackages)
                {
                    NapackMetadata affectedPackageMetadata = Global.NapackStorageManager.GetPackageMetadata(affectedPackage, true);
                    foreach (string authorizedUserId in affectedPackageMetadata.AuthorizedUserIds)
                    {
                        affectedUsers.Add(authorizedUserId);
                    }
                }

                // Send the emails now that we're all done.
                foreach (string authorizedUserId in metadata.AuthorizedUserIds)
                {
                    UserIdentifier user = Global.NapackStorageManager.GetUser(authorizedUserId);
                    Global.EmailManager.SendPackageDeletionEmail(user, packageName, false);
                    Global.NapackStorageManager.UpdateUser(user);
                }

                foreach (string authorizedUserId in affectedUsers)
                {
                    UserIdentifier user = Global.NapackStorageManager.GetUser(authorizedUserId);
                    Global.EmailManager.SendPackageDeletionEmail(user, packageName, true);
                    Global.NapackStorageManager.UpdateUser(user);
                }

                return(this.Response.AsJson(new
                {
                    AuthorizedUsersNotified = metadata.AuthorizedUserIds,
                    AffectedUsersNotified = affectedUsers,
                    Deleted = true
                }, HttpStatusCode.Gone));
            };
        }
 public void Deserialize_ThrowsOnNullData()
 {
     Assert.Throws <ArgumentNullException>(() => SerializerExtensions.Deserialize <object>(null, null));
 }
Ejemplo n.º 8
0
        public NapackModule()
            : base("/napacks")
        {
            // Gets a Napack package or series of package versions.
            Get["/{packageName}/{version?}"] = parameters =>
            {
                string packageName = parameters.packageName;
                string version     = null;
                try
                {
                    version = parameters.version;
                }
                catch (RuntimeBinderException)
                {
                }

                if (version == null)
                {
                    // The user is asking for all major versions of the specified package.
                    NapackMetadata package = Global.NapackStorageManager.GetPackageMetadata(packageName, false);
                    return(this.Response.AsJson(package.AsSummaryJson()));
                }
                else
                {
                    // Attempt to parse our the version string.
                    List <int> components;
                    try
                    {
                        components = version.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Select(item => int.Parse(item)).ToList();
                    }
                    catch (Exception)
                    {
                        throw new InvalidNapackVersionException();
                    }

                    // Handle the resulting version components.
                    if (components.Count == 1 || components.Count == 2)
                    {
                        NapackMetadata             package      = Global.NapackStorageManager.GetPackageMetadata(packageName, false);
                        NapackMajorVersionMetadata majorVersion = package.GetMajorVersion(components[0]);

                        return(this.Response.AsJson(majorVersion.AsSummaryJson()));
                    }
                    else if (components.Count == 3)
                    {
                        NapackVersion specificVersion = Global.NapackStorageManager.GetPackageVersion(new NapackVersionIdentifier(packageName, components[0], components[1], components[2]));
                        Global.NapackStorageManager.IncrementPackageDownload(packageName);

                        return(this.Response.AsJson(specificVersion.AsSummaryJson()));
                    }
                    else
                    {
                        throw new InvalidNapackVersionException();
                    }
                }
            };

            // Creates a new Napack package.
            Post["/{packageName}"] = parameters =>
            {
                string packageName = parameters.packageName;
                if (Global.NapackStorageManager.ContainsNapack(packageName))
                {
                    throw new DuplicateNapackException();
                }

                // Validate user, name and API.
                NewNapack newNapack = SerializerExtensions.Deserialize <NewNapack>(this.Context);
                newNapack.Validate();

                UserIdentifier.VerifyAuthorization(this.Request.Headers.ToDictionary(hdr => hdr.Key, hdr => hdr.Value), Global.NapackStorageManager, newNapack.metadata.AuthorizedUserIds);
                NapackSpec generatedApiSpec = NapackAnalyst.CreateNapackSpec(packageName, newNapack.NewNapackVersion.Files);
                NapackModule.ValidateDependentPackages(Global.NapackStorageManager, newNapack.NewNapackVersion);

                newNapack.NewNapackVersion.UpdateNamespaceOfFiles(packageName, 1);
                Global.NapackStorageManager.SaveNewNapack(packageName, newNapack, generatedApiSpec);

                return(this.Response.AsJson(new
                {
                    Message = "Created package " + packageName
                }, HttpStatusCode.Created));
            };

            // Updates the definition (metadata) of a Napack package.
            Put["/{packageName"] = parameters =>
            {
                string         packageName = parameters.packageName;
                NapackMetadata package     = Global.NapackStorageManager.GetPackageMetadata(packageName, true);

                NewNapackMetadata metadata = SerializerExtensions.Deserialize <NewNapackMetadata>(this.Context);
                UserIdentifier.VerifyAuthorization(this.Request.Headers.ToDictionary(hdr => hdr.Key, hdr => hdr.Value), Global.NapackStorageManager, metadata.AuthorizedUserIds);

                if (metadata.AuthorizedUserIds.Count == 0)
                {
                    throw new InvalidNapackException("At least one authorized user ID must be provided.");
                }

                package.AuthorizedUserIds = metadata.AuthorizedUserIds;
                package.Description       = metadata.Description;
                package.MoreInformation   = metadata.MoreInformation;
                package.Tags = metadata.Tags;
                Global.NapackStorageManager.UpdatePackageMetadata(package);

                return(this.Response.AsJson(new
                {
                    Message = "Updated package metadata " + packageName
                }));
            };

            // Updates an existing Napack package.
            Patch["/{packageName}"] = parameters =>
            {
                NewNapackVersion newNapackVersion = SerializerExtensions.Deserialize <NewNapackVersion>(this.Context);
                newNapackVersion.Validate();

                string         packageName = parameters.packageName;
                NapackMetadata package     = Global.NapackStorageManager.GetPackageMetadata(packageName, true);
                UserIdentifier.VerifyAuthorization(this.Request.Headers.ToDictionary(hdr => hdr.Key, hdr => hdr.Value), Global.NapackStorageManager, package.AuthorizedUserIds);

                // Validate and create a spec for this new version.
                NapackSpec newVersionSpec = NapackAnalyst.CreateNapackSpec(packageName, newNapackVersion.Files);
                NapackModule.ValidateDependentPackages(Global.NapackStorageManager, newNapackVersion);

                // Determine what upversioning will be performed.
                int majorVersion = package.Versions.Max(version => version.Key);
                int minorVersion = package.Versions[majorVersion].Versions.Max(version => version.Key);
                int patchVersion = package.Versions[majorVersion].Versions[minorVersion].Max();

                NapackAnalyst.UpversionType upversionType = NapackAnalyst.UpversionType.Patch;
                if (newNapackVersion.ForceMajorUpversioning)
                {
                    // Skip analysis as we know we must go to a new major version.
                    upversionType = NapackAnalyst.UpversionType.Major;
                }
                else
                {
                    // Perform specification and license analysis.
                    NapackVersionIdentifier oldVersionId          = new NapackVersionIdentifier(packageName, majorVersion, minorVersion, patchVersion);
                    NapackSpec oldVersionSpec                     = Global.NapackStorageManager.GetPackageSpecification(oldVersionId);
                    NapackAnalyst.UpversionType specUpversionType = NapackAnalyst.DeterminedRequiredUpversioning(oldVersionSpec, newVersionSpec);
                    if (specUpversionType == NapackAnalyst.UpversionType.Major || newNapackVersion.License.NeedsMajorUpversioning(package.GetMajorVersion(majorVersion).License))
                    {
                        upversionType = NapackAnalyst.UpversionType.Major;
                    }
                }

                if (upversionType == NapackAnalyst.UpversionType.Patch && newNapackVersion.ForceMinorUpversioning)
                {
                    upversionType = NapackAnalyst.UpversionType.Minor;
                }

                newNapackVersion.UpdateNamespaceOfFiles(packageName, upversionType != NapackAnalyst.UpversionType.Major ? majorVersion : majorVersion + 1);
                Global.NapackStorageManager.SaveNewNapackVersion(package, new NapackVersionIdentifier(packageName, majorVersion, minorVersion, patchVersion), upversionType, newNapackVersion, newVersionSpec);

                return(this.Response.AsJson(new
                {
                    Message = "Updated package " + packageName,
                    Major = majorVersion,
                    Minor = minorVersion,
                    Patch = patchVersion
                }));
            };
        }
Ejemplo n.º 9
0
        public void DeSerializeNull()
        {
            var final = SerializerExtensions.Deserialize <string>(null);

            Assert.IsNull(final);
        }