2
0

ApiServiceCollectionExtensions.cs 18 KB

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