PluginManagerTests.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. using System;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Text.Json;
  5. using System.Threading.Tasks;
  6. using AutoFixture;
  7. using Emby.Server.Implementations.Library;
  8. using Emby.Server.Implementations.Plugins;
  9. using Jellyfin.Extensions.Json;
  10. using Jellyfin.Extensions.Json.Converters;
  11. using MediaBrowser.Common.Plugins;
  12. using MediaBrowser.Model.Plugins;
  13. using MediaBrowser.Model.Updates;
  14. using Microsoft.Extensions.Logging.Abstractions;
  15. using Xunit;
  16. namespace Jellyfin.Server.Implementations.Tests.Plugins
  17. {
  18. public class PluginManagerTests
  19. {
  20. private static readonly string _testPathRoot = Path.Combine(Path.GetTempPath(), "jellyfin-test-data");
  21. private string _tempPath = string.Empty;
  22. private string _pluginPath = string.Empty;
  23. private JsonSerializerOptions _options;
  24. public PluginManagerTests()
  25. {
  26. (_tempPath, _pluginPath) = GetTestPaths("plugin-" + Path.GetRandomFileName());
  27. Directory.CreateDirectory(_pluginPath);
  28. _options = GetTestSerializerOptions();
  29. }
  30. [Fact]
  31. public void SaveManifest_RoundTrip_Success()
  32. {
  33. var pluginManager = new PluginManager(new NullLogger<PluginManager>(), null!, null!, null!, new Version(1, 0));
  34. var manifest = new PluginManifest()
  35. {
  36. Version = "1.0"
  37. };
  38. Assert.True(pluginManager.SaveManifest(manifest, _pluginPath));
  39. var res = pluginManager.LoadManifest(_pluginPath);
  40. Assert.Equal(manifest.Category, res.Manifest.Category);
  41. Assert.Equal(manifest.Changelog, res.Manifest.Changelog);
  42. Assert.Equal(manifest.Description, res.Manifest.Description);
  43. Assert.Equal(manifest.Id, res.Manifest.Id);
  44. Assert.Equal(manifest.Name, res.Manifest.Name);
  45. Assert.Equal(manifest.Overview, res.Manifest.Overview);
  46. Assert.Equal(manifest.Owner, res.Manifest.Owner);
  47. Assert.Equal(manifest.TargetAbi, res.Manifest.TargetAbi);
  48. Assert.Equal(manifest.Timestamp, res.Manifest.Timestamp);
  49. Assert.Equal(manifest.Version, res.Manifest.Version);
  50. Assert.Equal(manifest.Status, res.Manifest.Status);
  51. Assert.Equal(manifest.AutoUpdate, res.Manifest.AutoUpdate);
  52. Assert.Equal(manifest.ImagePath, res.Manifest.ImagePath);
  53. Assert.Equal(manifest.Assemblies, res.Manifest.Assemblies);
  54. }
  55. /// <summary>
  56. /// Tests safe traversal within the plugin directory.
  57. /// </summary>
  58. /// <param name="dllFile">The safe path to evaluate.</param>
  59. [Theory]
  60. [InlineData("./some.dll")]
  61. [InlineData("some.dll")]
  62. [InlineData("sub/path/some.dll")]
  63. public void Constructor_DiscoversSafePluginAssembly_Status_Active(string dllFile)
  64. {
  65. var manifest = new PluginManifest
  66. {
  67. Id = Guid.NewGuid(),
  68. Name = "Safe Assembly",
  69. Assemblies = new string[] { dllFile }
  70. };
  71. var filename = Path.GetFileName(dllFile)!;
  72. var dllPath = Path.GetDirectoryName(Path.Combine(_pluginPath, dllFile))!;
  73. Directory.CreateDirectory(dllPath);
  74. File.Create(Path.Combine(dllPath, filename));
  75. var metafilePath = Path.Combine(_pluginPath, "meta.json");
  76. File.WriteAllText(metafilePath, JsonSerializer.Serialize(manifest, _options));
  77. var pluginManager = new PluginManager(new NullLogger<PluginManager>(), null!, null!, _tempPath, new Version(1, 0));
  78. var res = JsonSerializer.Deserialize<PluginManifest>(File.ReadAllText(metafilePath), _options);
  79. var expectedFullPath = Path.Combine(_pluginPath, dllFile).Canonicalize();
  80. Assert.NotNull(res);
  81. Assert.NotEmpty(pluginManager.Plugins);
  82. Assert.Equal(PluginStatus.Active, res!.Status);
  83. Assert.Equal(expectedFullPath, pluginManager.Plugins[0].DllFiles[0]);
  84. Assert.StartsWith(_pluginPath, expectedFullPath, StringComparison.InvariantCulture);
  85. }
  86. /// <summary>
  87. /// Tests unsafe attempts to traverse to higher directories.
  88. /// </summary>
  89. /// <remarks>
  90. /// Attempts to load directories outside of the plugin should be
  91. /// constrained. Path traversal, shell expansion, and double encoding
  92. /// can be used to load unintended files.
  93. /// See <see href="https://owasp.org/www-community/attacks/Path_Traversal"/> for more.
  94. /// </remarks>
  95. /// <param name="unsafePath">The unsafe path to evaluate.</param>
  96. [Theory]
  97. [InlineData("/some.dll")] // Root path.
  98. [InlineData("../some.dll")] // Simple traversal.
  99. [InlineData("C:\\some.dll")] // Windows root path.
  100. [InlineData("test.txt")] // Not a DLL
  101. [InlineData(".././.././../some.dll")] // Traversal with current and parent
  102. [InlineData("..\\.\\..\\.\\..\\some.dll")] // Windows traversal with current and parent
  103. [InlineData("\\\\network\\resource.dll")] // UNC Path
  104. [InlineData("https://jellyfin.org/some.dll")] // URL
  105. [InlineData("~/some.dll")] // Tilde poses a shell expansion risk, but is a valid path character.
  106. public void Constructor_DiscoversUnsafePluginAssembly_Status_Malfunctioned(string unsafePath)
  107. {
  108. var manifest = new PluginManifest
  109. {
  110. Id = Guid.NewGuid(),
  111. Name = "Unsafe Assembly",
  112. Assemblies = new string[] { unsafePath }
  113. };
  114. // Only create very specific files. Otherwise the test will be exploiting path traversal.
  115. var files = new string[]
  116. {
  117. "../other.dll",
  118. "some.dll"
  119. };
  120. foreach (var file in files)
  121. {
  122. File.Create(Path.Combine(_pluginPath, file));
  123. }
  124. var metafilePath = Path.Combine(_pluginPath, "meta.json");
  125. File.WriteAllText(metafilePath, JsonSerializer.Serialize(manifest, _options));
  126. var pluginManager = new PluginManager(new NullLogger<PluginManager>(), null!, null!, _tempPath, new Version(1, 0));
  127. var res = JsonSerializer.Deserialize<PluginManifest>(File.ReadAllText(metafilePath), _options);
  128. Assert.NotNull(res);
  129. Assert.Empty(pluginManager.Plugins);
  130. Assert.Equal(PluginStatus.Malfunctioned, res!.Status);
  131. }
  132. [Fact]
  133. public async Task PopulateManifest_ExistingMetafilePlugin_PopulatesMissingFields()
  134. {
  135. var packageInfo = GenerateTestPackage();
  136. // Partial plugin without a name, but matching version and package ID
  137. var partial = new PluginManifest
  138. {
  139. Id = packageInfo.Id,
  140. AutoUpdate = false, // Turn off AutoUpdate
  141. Status = PluginStatus.Restart,
  142. Version = new Version(1, 0, 0).ToString(),
  143. Assemblies = new[] { "Jellyfin.Test.dll" }
  144. };
  145. var metafilePath = Path.Combine(_pluginPath, "meta.json");
  146. File.WriteAllText(metafilePath, JsonSerializer.Serialize(partial, _options));
  147. var pluginManager = new PluginManager(new NullLogger<PluginManager>(), null!, null!, _tempPath, new Version(1, 0));
  148. await pluginManager.PopulateManifest(packageInfo, new Version(1, 0), _pluginPath, PluginStatus.Active);
  149. var resultBytes = File.ReadAllBytes(metafilePath);
  150. var result = JsonSerializer.Deserialize<PluginManifest>(resultBytes, _options);
  151. Assert.NotNull(result);
  152. Assert.Equal(packageInfo.Name, result.Name);
  153. Assert.Equal(packageInfo.Owner, result.Owner);
  154. Assert.Equal(PluginStatus.Active, result.Status);
  155. Assert.NotEmpty(result.Assemblies);
  156. Assert.False(result.AutoUpdate);
  157. // Preserved
  158. Assert.Equal(packageInfo.Category, result.Category);
  159. Assert.Equal(packageInfo.Description, result.Description);
  160. Assert.Equal(packageInfo.Id, result.Id);
  161. Assert.Equal(packageInfo.Overview, result.Overview);
  162. Assert.Equal(partial.Assemblies[0], result.Assemblies[0]);
  163. Assert.Equal(packageInfo.Versions[0].TargetAbi, result.TargetAbi);
  164. Assert.Equal(DateTime.Parse(packageInfo.Versions[0].Timestamp!, CultureInfo.InvariantCulture), result.Timestamp);
  165. Assert.Equal(packageInfo.Versions[0].Changelog, result.Changelog);
  166. Assert.Equal(packageInfo.Versions[0].Version, result.Version);
  167. }
  168. [Fact]
  169. public async Task PopulateManifest_ExistingMetafileMismatchedIds_Status_Malfunctioned()
  170. {
  171. var packageInfo = GenerateTestPackage();
  172. // Partial plugin without a name, but matching version and package ID
  173. var partial = new PluginManifest
  174. {
  175. Id = Guid.NewGuid(),
  176. Version = new Version(1, 0, 0).ToString()
  177. };
  178. var metafilePath = Path.Combine(_pluginPath, "meta.json");
  179. File.WriteAllText(metafilePath, JsonSerializer.Serialize(partial, _options));
  180. var pluginManager = new PluginManager(new NullLogger<PluginManager>(), null!, null!, _tempPath, new Version(1, 0));
  181. await pluginManager.PopulateManifest(packageInfo, new Version(1, 0), _pluginPath, PluginStatus.Active);
  182. var resultBytes = File.ReadAllBytes(metafilePath);
  183. var result = JsonSerializer.Deserialize<PluginManifest>(resultBytes, _options);
  184. Assert.NotNull(result);
  185. Assert.Equal(packageInfo.Name, result.Name);
  186. Assert.Equal(PluginStatus.Malfunctioned, result.Status);
  187. }
  188. [Fact]
  189. public async Task PopulateManifest_ExistingMetafileMismatchedVersions_Updates_Version()
  190. {
  191. var packageInfo = GenerateTestPackage();
  192. var partial = new PluginManifest
  193. {
  194. Id = packageInfo.Id,
  195. Version = new Version(2, 0, 0).ToString()
  196. };
  197. var metafilePath = Path.Combine(_pluginPath, "meta.json");
  198. File.WriteAllText(metafilePath, JsonSerializer.Serialize(partial, _options));
  199. var pluginManager = new PluginManager(new NullLogger<PluginManager>(), null!, null!, _tempPath, new Version(1, 0));
  200. await pluginManager.PopulateManifest(packageInfo, new Version(1, 0), _pluginPath, PluginStatus.Active);
  201. var resultBytes = File.ReadAllBytes(metafilePath);
  202. var result = JsonSerializer.Deserialize<PluginManifest>(resultBytes, _options);
  203. Assert.NotNull(result);
  204. Assert.Equal(packageInfo.Name, result.Name);
  205. Assert.Equal(PluginStatus.Active, result.Status);
  206. Assert.Equal(packageInfo.Versions[0].Version, result.Version);
  207. }
  208. private PackageInfo GenerateTestPackage()
  209. {
  210. var fixture = new Fixture();
  211. fixture.Customize<PackageInfo>(c => c.Without(x => x.Versions).Without(x => x.ImageUrl));
  212. fixture.Customize<VersionInfo>(c => c.Without(x => x.Version).Without(x => x.Timestamp));
  213. var versionInfo = fixture.Create<VersionInfo>();
  214. versionInfo.Version = new Version(1, 0).ToString();
  215. versionInfo.Timestamp = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture);
  216. var packageInfo = fixture.Create<PackageInfo>();
  217. packageInfo.Versions = new[] { versionInfo };
  218. return packageInfo;
  219. }
  220. private JsonSerializerOptions GetTestSerializerOptions()
  221. {
  222. var options = new JsonSerializerOptions(JsonDefaults.Options)
  223. {
  224. WriteIndented = true
  225. };
  226. for (var i = 0; i < options.Converters.Count; i++)
  227. {
  228. // Remove the Guid converter for parity with plugin manager.
  229. if (options.Converters[i] is JsonGuidConverter converter)
  230. {
  231. options.Converters.Remove(converter);
  232. }
  233. }
  234. return options;
  235. }
  236. private (string TempPath, string PluginPath) GetTestPaths(string pluginFolderName)
  237. {
  238. var tempPath = Path.Combine(_testPathRoot, "plugin-manager" + Path.GetRandomFileName());
  239. var pluginPath = Path.Combine(tempPath, pluginFolderName);
  240. return (tempPath, pluginPath);
  241. }
  242. }
  243. }