ApiServiceCollectionExtensions.cs 19 KB

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