ApiServiceCollectionExtensions.cs 18 KB

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