2
0

ApiServiceCollectionExtensions.cs 22 KB

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