ApiServiceCollectionExtensions.cs 18 KB

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