ApiServiceCollectionExtensions.cs 20 KB

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