ApiServiceCollectionExtensions.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Reflection;
  8. using Emby.Server.Implementations;
  9. using Jellyfin.Api.Auth;
  10. using Jellyfin.Api.Auth.DefaultAuthorizationPolicy;
  11. using Jellyfin.Api.Auth.DownloadPolicy;
  12. using Jellyfin.Api.Auth.FirstTimeOrIgnoreParentalControlSetupPolicy;
  13. using Jellyfin.Api.Auth.FirstTimeSetupOrDefaultPolicy;
  14. using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy;
  15. using Jellyfin.Api.Auth.IgnoreParentalControlPolicy;
  16. using Jellyfin.Api.Auth.LocalAccessOrRequiresElevationPolicy;
  17. using Jellyfin.Api.Auth.LocalAccessPolicy;
  18. using Jellyfin.Api.Auth.RequiresElevationPolicy;
  19. using Jellyfin.Api.Auth.SyncPlayAccessPolicy;
  20. using Jellyfin.Api.Constants;
  21. using Jellyfin.Api.Controllers;
  22. using Jellyfin.Api.ModelBinders;
  23. using Jellyfin.Data.Enums;
  24. using Jellyfin.Extensions.Json;
  25. using Jellyfin.Networking.Configuration;
  26. using Jellyfin.Server.Configuration;
  27. using Jellyfin.Server.Filters;
  28. using Jellyfin.Server.Formatters;
  29. using MediaBrowser.Common.Net;
  30. using MediaBrowser.Model.Entities;
  31. using Microsoft.AspNetCore.Authentication;
  32. using Microsoft.AspNetCore.Authorization;
  33. using Microsoft.AspNetCore.Builder;
  34. using Microsoft.AspNetCore.Cors.Infrastructure;
  35. using Microsoft.AspNetCore.HttpOverrides;
  36. using Microsoft.Extensions.DependencyInjection;
  37. using Microsoft.OpenApi.Any;
  38. using Microsoft.OpenApi.Interfaces;
  39. using Microsoft.OpenApi.Models;
  40. using Swashbuckle.AspNetCore.SwaggerGen;
  41. using AuthenticationSchemes = Jellyfin.Api.Constants.AuthenticationSchemes;
  42. namespace Jellyfin.Server.Extensions
  43. {
  44. /// <summary>
  45. /// API specific extensions for the service collection.
  46. /// </summary>
  47. public static class ApiServiceCollectionExtensions
  48. {
  49. /// <summary>
  50. /// Adds jellyfin API authorization policies to the DI container.
  51. /// </summary>
  52. /// <param name="serviceCollection">The service collection.</param>
  53. /// <returns>The updated service collection.</returns>
  54. public static IServiceCollection AddJellyfinApiAuthorization(this IServiceCollection serviceCollection)
  55. {
  56. serviceCollection.AddSingleton<IAuthorizationHandler, DefaultAuthorizationHandler>();
  57. serviceCollection.AddSingleton<IAuthorizationHandler, DownloadHandler>();
  58. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrDefaultHandler>();
  59. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrElevatedHandler>();
  60. serviceCollection.AddSingleton<IAuthorizationHandler, IgnoreParentalControlHandler>();
  61. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeOrIgnoreParentalControlSetupHandler>();
  62. serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessHandler>();
  63. serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessOrRequiresElevationHandler>();
  64. serviceCollection.AddSingleton<IAuthorizationHandler, RequiresElevationHandler>();
  65. serviceCollection.AddSingleton<IAuthorizationHandler, SyncPlayAccessHandler>();
  66. return serviceCollection.AddAuthorizationCore(options =>
  67. {
  68. options.AddPolicy(
  69. Policies.DefaultAuthorization,
  70. policy =>
  71. {
  72. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  73. policy.AddRequirements(new DefaultAuthorizationRequirement());
  74. });
  75. options.AddPolicy(
  76. Policies.Download,
  77. policy =>
  78. {
  79. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  80. policy.AddRequirements(new DownloadRequirement());
  81. });
  82. options.AddPolicy(
  83. Policies.FirstTimeSetupOrDefault,
  84. policy =>
  85. {
  86. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  87. policy.AddRequirements(new FirstTimeSetupOrDefaultRequirement());
  88. });
  89. options.AddPolicy(
  90. Policies.FirstTimeSetupOrElevated,
  91. policy =>
  92. {
  93. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  94. policy.AddRequirements(new FirstTimeSetupOrElevatedRequirement());
  95. });
  96. options.AddPolicy(
  97. Policies.IgnoreParentalControl,
  98. policy =>
  99. {
  100. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  101. policy.AddRequirements(new IgnoreParentalControlRequirement());
  102. });
  103. options.AddPolicy(
  104. Policies.FirstTimeSetupOrIgnoreParentalControl,
  105. policy =>
  106. {
  107. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  108. policy.AddRequirements(new FirstTimeOrIgnoreParentalControlSetupRequirement());
  109. });
  110. options.AddPolicy(
  111. Policies.LocalAccessOnly,
  112. policy =>
  113. {
  114. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  115. policy.AddRequirements(new LocalAccessRequirement());
  116. });
  117. options.AddPolicy(
  118. Policies.LocalAccessOrRequiresElevation,
  119. policy =>
  120. {
  121. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  122. policy.AddRequirements(new LocalAccessOrRequiresElevationRequirement());
  123. });
  124. options.AddPolicy(
  125. Policies.RequiresElevation,
  126. policy =>
  127. {
  128. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  129. policy.AddRequirements(new RequiresElevationRequirement());
  130. });
  131. options.AddPolicy(
  132. Policies.SyncPlayHasAccess,
  133. policy =>
  134. {
  135. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  136. policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.HasAccess));
  137. });
  138. options.AddPolicy(
  139. Policies.SyncPlayCreateGroup,
  140. policy =>
  141. {
  142. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  143. policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.CreateGroup));
  144. });
  145. options.AddPolicy(
  146. Policies.SyncPlayJoinGroup,
  147. policy =>
  148. {
  149. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  150. policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.JoinGroup));
  151. });
  152. options.AddPolicy(
  153. Policies.SyncPlayIsInGroup,
  154. policy =>
  155. {
  156. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  157. policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.IsInGroup));
  158. });
  159. });
  160. }
  161. /// <summary>
  162. /// Adds custom legacy authentication to the service collection.
  163. /// </summary>
  164. /// <param name="serviceCollection">The service collection.</param>
  165. /// <returns>The updated service collection.</returns>
  166. public static AuthenticationBuilder AddCustomAuthentication(this IServiceCollection serviceCollection)
  167. {
  168. return serviceCollection.AddAuthentication(AuthenticationSchemes.CustomAuthentication)
  169. .AddScheme<AuthenticationSchemeOptions, CustomAuthenticationHandler>(AuthenticationSchemes.CustomAuthentication, null);
  170. }
  171. /// <summary>
  172. /// Extension method for adding the jellyfin API to the service collection.
  173. /// </summary>
  174. /// <param name="serviceCollection">The service collection.</param>
  175. /// <param name="pluginAssemblies">An IEnumerable containing all plugin assemblies with API controllers.</param>
  176. /// <param name="config">The <see cref="NetworkConfiguration"/>.</param>
  177. /// <returns>The MVC builder.</returns>
  178. public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable<Assembly> pluginAssemblies, NetworkConfiguration config)
  179. {
  180. IMvcBuilder mvcBuilder = serviceCollection
  181. .AddCors()
  182. .AddTransient<ICorsPolicyProvider, CorsPolicyProvider>()
  183. .Configure<ForwardedHeadersOptions>(options =>
  184. {
  185. // https://github.com/dotnet/aspnetcore/blob/master/src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs
  186. // Enable debug logging on Microsoft.AspNetCore.HttpOverrides.ForwardedHeadersMiddleware to help investigate issues.
  187. options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
  188. if (config.KnownProxies.Length == 0)
  189. {
  190. options.KnownNetworks.Clear();
  191. options.KnownProxies.Clear();
  192. }
  193. else
  194. {
  195. AddProxyAddresses(config, config.KnownProxies, options);
  196. }
  197. // Only set forward limit if we have some known proxies or some known networks.
  198. if (options.KnownProxies.Count != 0 || options.KnownNetworks.Count != 0)
  199. {
  200. options.ForwardLimit = null;
  201. }
  202. })
  203. .AddMvc(opts =>
  204. {
  205. // Allow requester to change between camelCase and PascalCase
  206. opts.RespectBrowserAcceptHeader = true;
  207. opts.OutputFormatters.Insert(0, new CamelCaseJsonProfileFormatter());
  208. opts.OutputFormatters.Insert(0, new PascalCaseJsonProfileFormatter());
  209. opts.OutputFormatters.Add(new CssOutputFormatter());
  210. opts.OutputFormatters.Add(new XmlOutputFormatter());
  211. opts.ModelBinderProviders.Insert(0, new NullableEnumModelBinderProvider());
  212. })
  213. // Clear app parts to avoid other assemblies being picked up
  214. .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear())
  215. .AddApplicationPart(typeof(StartupController).Assembly)
  216. .AddJsonOptions(options =>
  217. {
  218. // Update all properties that are set in JsonDefaults
  219. var jsonOptions = JsonDefaults.PascalCaseOptions;
  220. // From JsonDefaults
  221. options.JsonSerializerOptions.ReadCommentHandling = jsonOptions.ReadCommentHandling;
  222. options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented;
  223. options.JsonSerializerOptions.DefaultIgnoreCondition = jsonOptions.DefaultIgnoreCondition;
  224. options.JsonSerializerOptions.NumberHandling = jsonOptions.NumberHandling;
  225. options.JsonSerializerOptions.Converters.Clear();
  226. foreach (var converter in jsonOptions.Converters)
  227. {
  228. options.JsonSerializerOptions.Converters.Add(converter);
  229. }
  230. // From JsonDefaults.PascalCase
  231. options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy;
  232. });
  233. foreach (Assembly pluginAssembly in pluginAssemblies)
  234. {
  235. mvcBuilder.AddApplicationPart(pluginAssembly);
  236. }
  237. return mvcBuilder.AddControllersAsServices();
  238. }
  239. /// <summary>
  240. /// Adds Swagger to the service collection.
  241. /// </summary>
  242. /// <param name="serviceCollection">The service collection.</param>
  243. /// <returns>The updated service collection.</returns>
  244. public static IServiceCollection AddJellyfinApiSwagger(this IServiceCollection serviceCollection)
  245. {
  246. return serviceCollection.AddSwaggerGen(c =>
  247. {
  248. var version = typeof(ApplicationHost).Assembly.GetName().Version?.ToString(3) ?? "0.0.1";
  249. c.SwaggerDoc("api-docs", new OpenApiInfo
  250. {
  251. Title = "Jellyfin API",
  252. Version = version,
  253. Extensions = new Dictionary<string, IOpenApiExtension>
  254. {
  255. {
  256. "x-jellyfin-version",
  257. new OpenApiString(version)
  258. }
  259. }
  260. });
  261. c.AddSecurityDefinition(AuthenticationSchemes.CustomAuthentication, new OpenApiSecurityScheme
  262. {
  263. Type = SecuritySchemeType.ApiKey,
  264. In = ParameterLocation.Header,
  265. Name = "X-Emby-Authorization",
  266. Description = "API key header parameter"
  267. });
  268. // Add all xml doc files to swagger generator.
  269. var xmlFiles = Directory.GetFiles(
  270. AppContext.BaseDirectory,
  271. "*.xml",
  272. SearchOption.TopDirectoryOnly);
  273. foreach (var xmlFile in xmlFiles)
  274. {
  275. c.IncludeXmlComments(xmlFile);
  276. }
  277. // Order actions by route path, then by http method.
  278. c.OrderActionsBy(description =>
  279. $"{description.ActionDescriptor.RouteValues["controller"]}_{description.RelativePath}");
  280. // Use method name as operationId
  281. c.CustomOperationIds(
  282. description =>
  283. {
  284. description.TryGetMethodInfo(out MethodInfo methodInfo);
  285. // Attribute name, method name, none.
  286. return description?.ActionDescriptor?.AttributeRouteInfo?.Name
  287. ?? methodInfo?.Name
  288. ?? null;
  289. });
  290. // Allow parameters to properly be nullable.
  291. c.UseAllOfToExtendReferenceSchemas();
  292. c.SupportNonNullableReferenceTypes();
  293. // TODO - remove when all types are supported in System.Text.Json
  294. c.AddSwaggerTypeMappings();
  295. c.OperationFilter<SecurityRequirementsOperationFilter>();
  296. c.OperationFilter<FileResponseFilter>();
  297. c.OperationFilter<FileRequestFilter>();
  298. c.OperationFilter<ParameterObsoleteFilter>();
  299. c.DocumentFilter<AdditionalModelFilter>();
  300. });
  301. }
  302. /// <summary>
  303. /// Sets up the proxy configuration based on the addresses in <paramref name="allowedProxies"/>.
  304. /// </summary>
  305. /// <param name="config">The <see cref="NetworkConfiguration"/> containing the config settings.</param>
  306. /// <param name="allowedProxies">The string array to parse.</param>
  307. /// <param name="options">The <see cref="ForwardedHeadersOptions"/> instance.</param>
  308. internal static void AddProxyAddresses(NetworkConfiguration config, string[] allowedProxies, ForwardedHeadersOptions options)
  309. {
  310. for (var i = 0; i < allowedProxies.Length; i++)
  311. {
  312. if (IPNetAddress.TryParse(allowedProxies[i], out var addr))
  313. {
  314. AddIpAddress(config, options, addr.Address, addr.PrefixLength);
  315. }
  316. else if (IPHost.TryParse(allowedProxies[i], out var host))
  317. {
  318. foreach (var address in host.GetAddresses())
  319. {
  320. AddIpAddress(config, options, addr.Address, addr.PrefixLength);
  321. }
  322. }
  323. }
  324. }
  325. private static void AddIpAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength)
  326. {
  327. if ((!config.EnableIPV4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPV6 && addr.AddressFamily == AddressFamily.InterNetworkV6))
  328. {
  329. return;
  330. }
  331. // In order for dual-mode sockets to be used, IP6 has to be enabled in JF and an interface has to have an IP6 address.
  332. if (addr.AddressFamily == AddressFamily.InterNetwork && config.EnableIPV6)
  333. {
  334. // If the server is using dual-mode sockets, IPv4 addresses are supplied in an IPv6 format.
  335. // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0 .
  336. addr = addr.MapToIPv6();
  337. }
  338. if (prefixLength == 32)
  339. {
  340. options.KnownProxies.Add(addr);
  341. }
  342. else
  343. {
  344. options.KnownNetworks.Add(new IPNetwork(addr, prefixLength));
  345. }
  346. }
  347. private static void AddSwaggerTypeMappings(this SwaggerGenOptions options)
  348. {
  349. /*
  350. * TODO remove when System.Text.Json properly supports non-string keys.
  351. * Used in BaseItemDto.ImageBlurHashes
  352. */
  353. options.MapType<Dictionary<ImageType, string>>(() =>
  354. new OpenApiSchema
  355. {
  356. Type = "object",
  357. AdditionalProperties = new OpenApiSchema
  358. {
  359. Type = "string"
  360. }
  361. });
  362. /*
  363. * Support BlurHash dictionary
  364. */
  365. options.MapType<Dictionary<ImageType, Dictionary<string, string>>>(() =>
  366. new OpenApiSchema
  367. {
  368. Type = "object",
  369. Properties = typeof(ImageType).GetEnumNames().ToDictionary(
  370. name => name,
  371. name => new OpenApiSchema
  372. {
  373. Type = "object",
  374. AdditionalProperties = new OpenApiSchema
  375. {
  376. Type = "string"
  377. }
  378. })
  379. });
  380. }
  381. }
  382. }