ApiServiceCollectionExtensions.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Reflection;
  7. using Emby.Server.Implementations;
  8. using Jellyfin.Api.Auth;
  9. using Jellyfin.Api.Auth.DefaultAuthorizationPolicy;
  10. using Jellyfin.Api.Auth.DownloadPolicy;
  11. using Jellyfin.Api.Auth.FirstTimeOrIgnoreParentalControlSetupPolicy;
  12. using Jellyfin.Api.Auth.FirstTimeSetupOrDefaultPolicy;
  13. using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy;
  14. using Jellyfin.Api.Auth.IgnoreParentalControlPolicy;
  15. using Jellyfin.Api.Auth.LocalAccessOrRequiresElevationPolicy;
  16. using Jellyfin.Api.Auth.LocalAccessPolicy;
  17. using Jellyfin.Api.Auth.RequiresElevationPolicy;
  18. using Jellyfin.Api.Auth.SyncPlayAccessPolicy;
  19. using Jellyfin.Api.Constants;
  20. using Jellyfin.Api.Controllers;
  21. using Jellyfin.Api.ModelBinders;
  22. using Jellyfin.Data.Enums;
  23. using Jellyfin.Server.Configuration;
  24. using Jellyfin.Server.Filters;
  25. using Jellyfin.Server.Formatters;
  26. using MediaBrowser.Common.Json;
  27. using MediaBrowser.Model.Entities;
  28. using Microsoft.AspNetCore.Authentication;
  29. using Microsoft.AspNetCore.Authorization;
  30. using Microsoft.AspNetCore.Builder;
  31. using Microsoft.AspNetCore.Cors.Infrastructure;
  32. using Microsoft.AspNetCore.HttpOverrides;
  33. using Microsoft.Extensions.DependencyInjection;
  34. using Microsoft.OpenApi.Any;
  35. using Microsoft.OpenApi.Interfaces;
  36. using Microsoft.OpenApi.Models;
  37. using Swashbuckle.AspNetCore.SwaggerGen;
  38. using AuthenticationSchemes = Jellyfin.Api.Constants.AuthenticationSchemes;
  39. namespace Jellyfin.Server.Extensions
  40. {
  41. /// <summary>
  42. /// API specific extensions for the service collection.
  43. /// </summary>
  44. public static class ApiServiceCollectionExtensions
  45. {
  46. /// <summary>
  47. /// Adds jellyfin API authorization policies to the DI container.
  48. /// </summary>
  49. /// <param name="serviceCollection">The service collection.</param>
  50. /// <returns>The updated service collection.</returns>
  51. public static IServiceCollection AddJellyfinApiAuthorization(this IServiceCollection serviceCollection)
  52. {
  53. serviceCollection.AddSingleton<IAuthorizationHandler, DefaultAuthorizationHandler>();
  54. serviceCollection.AddSingleton<IAuthorizationHandler, DownloadHandler>();
  55. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrDefaultHandler>();
  56. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrElevatedHandler>();
  57. serviceCollection.AddSingleton<IAuthorizationHandler, IgnoreParentalControlHandler>();
  58. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeOrIgnoreParentalControlSetupHandler>();
  59. serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessHandler>();
  60. serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessOrRequiresElevationHandler>();
  61. serviceCollection.AddSingleton<IAuthorizationHandler, RequiresElevationHandler>();
  62. serviceCollection.AddSingleton<IAuthorizationHandler, SyncPlayAccessHandler>();
  63. return serviceCollection.AddAuthorizationCore(options =>
  64. {
  65. options.AddPolicy(
  66. Policies.DefaultAuthorization,
  67. policy =>
  68. {
  69. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  70. policy.AddRequirements(new DefaultAuthorizationRequirement());
  71. });
  72. options.AddPolicy(
  73. Policies.Download,
  74. policy =>
  75. {
  76. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  77. policy.AddRequirements(new DownloadRequirement());
  78. });
  79. options.AddPolicy(
  80. Policies.FirstTimeSetupOrDefault,
  81. policy =>
  82. {
  83. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  84. policy.AddRequirements(new FirstTimeSetupOrDefaultRequirement());
  85. });
  86. options.AddPolicy(
  87. Policies.FirstTimeSetupOrElevated,
  88. policy =>
  89. {
  90. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  91. policy.AddRequirements(new FirstTimeSetupOrElevatedRequirement());
  92. });
  93. options.AddPolicy(
  94. Policies.IgnoreParentalControl,
  95. policy =>
  96. {
  97. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  98. policy.AddRequirements(new IgnoreParentalControlRequirement());
  99. });
  100. options.AddPolicy(
  101. Policies.FirstTimeSetupOrIgnoreParentalControl,
  102. policy =>
  103. {
  104. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  105. policy.AddRequirements(new FirstTimeOrIgnoreParentalControlSetupRequirement());
  106. });
  107. options.AddPolicy(
  108. Policies.LocalAccessOnly,
  109. policy =>
  110. {
  111. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  112. policy.AddRequirements(new LocalAccessRequirement());
  113. });
  114. options.AddPolicy(
  115. Policies.LocalAccessOrRequiresElevation,
  116. policy =>
  117. {
  118. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  119. policy.AddRequirements(new LocalAccessOrRequiresElevationRequirement());
  120. });
  121. options.AddPolicy(
  122. Policies.RequiresElevation,
  123. policy =>
  124. {
  125. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  126. policy.AddRequirements(new RequiresElevationRequirement());
  127. });
  128. options.AddPolicy(
  129. Policies.SyncPlayHasAccess,
  130. policy =>
  131. {
  132. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  133. policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.HasAccess));
  134. });
  135. options.AddPolicy(
  136. Policies.SyncPlayCreateGroup,
  137. policy =>
  138. {
  139. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  140. policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.CreateGroup));
  141. });
  142. options.AddPolicy(
  143. Policies.SyncPlayJoinGroup,
  144. policy =>
  145. {
  146. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  147. policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.JoinGroup));
  148. });
  149. options.AddPolicy(
  150. Policies.SyncPlayIsInGroup,
  151. policy =>
  152. {
  153. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  154. policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.IsInGroup));
  155. });
  156. });
  157. }
  158. /// <summary>
  159. /// Adds custom legacy authentication to the service collection.
  160. /// </summary>
  161. /// <param name="serviceCollection">The service collection.</param>
  162. /// <returns>The updated service collection.</returns>
  163. public static AuthenticationBuilder AddCustomAuthentication(this IServiceCollection serviceCollection)
  164. {
  165. return serviceCollection.AddAuthentication(AuthenticationSchemes.CustomAuthentication)
  166. .AddScheme<AuthenticationSchemeOptions, CustomAuthenticationHandler>(AuthenticationSchemes.CustomAuthentication, null);
  167. }
  168. /// <summary>
  169. /// Extension method for adding the jellyfin API to the service collection.
  170. /// </summary>
  171. /// <param name="serviceCollection">The service collection.</param>
  172. /// <param name="pluginAssemblies">An IEnumerable containing all plugin assemblies with API controllers.</param>
  173. /// <param name="knownProxies">A list of all known proxies to trust for X-Forwarded-For.</param>
  174. /// <returns>The MVC builder.</returns>
  175. public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable<Assembly> pluginAssemblies, IReadOnlyList<string> knownProxies)
  176. {
  177. IMvcBuilder mvcBuilder = serviceCollection
  178. .AddCors()
  179. .AddTransient<ICorsPolicyProvider, CorsPolicyProvider>()
  180. .Configure<ForwardedHeadersOptions>(options =>
  181. {
  182. options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
  183. if (knownProxies.Count == 0)
  184. {
  185. options.KnownNetworks.Clear();
  186. options.KnownProxies.Clear();
  187. }
  188. else
  189. {
  190. for (var i = 0; i < knownProxies.Count; i++)
  191. {
  192. if (IPAddress.TryParse(knownProxies[i], out var address))
  193. {
  194. options.KnownProxies.Add(address);
  195. }
  196. }
  197. }
  198. })
  199. .AddMvc(opts =>
  200. {
  201. // Allow requester to change between camelCase and PascalCase
  202. opts.RespectBrowserAcceptHeader = true;
  203. opts.OutputFormatters.Insert(0, new CamelCaseJsonProfileFormatter());
  204. opts.OutputFormatters.Insert(0, new PascalCaseJsonProfileFormatter());
  205. opts.OutputFormatters.Add(new CssOutputFormatter());
  206. opts.OutputFormatters.Add(new XmlOutputFormatter());
  207. opts.ModelBinderProviders.Insert(0, new NullableEnumModelBinderProvider());
  208. })
  209. // Clear app parts to avoid other assemblies being picked up
  210. .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear())
  211. .AddApplicationPart(typeof(StartupController).Assembly)
  212. .AddJsonOptions(options =>
  213. {
  214. // Update all properties that are set in JsonDefaults
  215. var jsonOptions = JsonDefaults.GetPascalCaseOptions();
  216. // From JsonDefaults
  217. options.JsonSerializerOptions.ReadCommentHandling = jsonOptions.ReadCommentHandling;
  218. options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented;
  219. options.JsonSerializerOptions.DefaultIgnoreCondition = jsonOptions.DefaultIgnoreCondition;
  220. options.JsonSerializerOptions.NumberHandling = jsonOptions.NumberHandling;
  221. options.JsonSerializerOptions.Converters.Clear();
  222. foreach (var converter in jsonOptions.Converters)
  223. {
  224. options.JsonSerializerOptions.Converters.Add(converter);
  225. }
  226. // From JsonDefaults.PascalCase
  227. options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy;
  228. });
  229. foreach (Assembly pluginAssembly in pluginAssemblies)
  230. {
  231. mvcBuilder.AddApplicationPart(pluginAssembly);
  232. }
  233. return mvcBuilder.AddControllersAsServices();
  234. }
  235. /// <summary>
  236. /// Adds Swagger to the service collection.
  237. /// </summary>
  238. /// <param name="serviceCollection">The service collection.</param>
  239. /// <returns>The updated service collection.</returns>
  240. public static IServiceCollection AddJellyfinApiSwagger(this IServiceCollection serviceCollection)
  241. {
  242. return serviceCollection.AddSwaggerGen(c =>
  243. {
  244. c.SwaggerDoc("api-docs", new OpenApiInfo
  245. {
  246. Title = "Jellyfin API",
  247. Version = "v1",
  248. Extensions = new Dictionary<string, IOpenApiExtension>
  249. {
  250. {
  251. "x-jellyfin-version",
  252. new OpenApiString(typeof(ApplicationHost).Assembly.GetName().Version?.ToString())
  253. }
  254. }
  255. });
  256. c.AddSecurityDefinition(AuthenticationSchemes.CustomAuthentication, new OpenApiSecurityScheme
  257. {
  258. Type = SecuritySchemeType.ApiKey,
  259. In = ParameterLocation.Header,
  260. Name = "X-Emby-Authorization",
  261. Description = "API key header parameter"
  262. });
  263. // Add all xml doc files to swagger generator.
  264. var xmlFiles = Directory.GetFiles(
  265. AppContext.BaseDirectory,
  266. "*.xml",
  267. SearchOption.TopDirectoryOnly);
  268. foreach (var xmlFile in xmlFiles)
  269. {
  270. c.IncludeXmlComments(xmlFile);
  271. }
  272. // Order actions by route path, then by http method.
  273. c.OrderActionsBy(description =>
  274. $"{description.ActionDescriptor.RouteValues["controller"]}_{description.RelativePath}");
  275. // Use method name as operationId
  276. c.CustomOperationIds(
  277. description =>
  278. {
  279. description.TryGetMethodInfo(out MethodInfo methodInfo);
  280. // Attribute name, method name, none.
  281. return description?.ActionDescriptor?.AttributeRouteInfo?.Name
  282. ?? methodInfo?.Name
  283. ?? null;
  284. });
  285. // TODO - remove when all types are supported in System.Text.Json
  286. c.AddSwaggerTypeMappings();
  287. c.OperationFilter<SecurityRequirementsOperationFilter>();
  288. c.OperationFilter<FileResponseFilter>();
  289. c.DocumentFilter<WebsocketModelFilter>();
  290. });
  291. }
  292. private static void AddSwaggerTypeMappings(this SwaggerGenOptions options)
  293. {
  294. /*
  295. * TODO remove when System.Text.Json properly supports non-string keys.
  296. * Used in BaseItemDto.ImageBlurHashes
  297. */
  298. options.MapType<Dictionary<ImageType, string>>(() =>
  299. new OpenApiSchema
  300. {
  301. Type = "object",
  302. AdditionalProperties = new OpenApiSchema
  303. {
  304. Type = "string"
  305. }
  306. });
  307. /*
  308. * Support BlurHash dictionary
  309. */
  310. options.MapType<Dictionary<ImageType, Dictionary<string, string>>>(() =>
  311. new OpenApiSchema
  312. {
  313. Type = "object",
  314. Properties = typeof(ImageType).GetEnumNames().ToDictionary(
  315. name => name,
  316. name => new OpenApiSchema
  317. {
  318. Type = "object",
  319. AdditionalProperties = new OpenApiSchema
  320. {
  321. Type = "string"
  322. }
  323. })
  324. });
  325. }
  326. }
  327. }