ApiServiceCollectionExtensions.cs 17 KB

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