2
0

ApiServiceCollectionExtensions.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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.Common.Net;
  28. using MediaBrowser.Model.Entities;
  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. serviceCollection.AddSingleton<IAuthorizationHandler, DefaultAuthorizationHandler>();
  55. serviceCollection.AddSingleton<IAuthorizationHandler, DownloadHandler>();
  56. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrDefaultHandler>();
  57. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrElevatedHandler>();
  58. serviceCollection.AddSingleton<IAuthorizationHandler, IgnoreParentalControlHandler>();
  59. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeOrIgnoreParentalControlSetupHandler>();
  60. serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessHandler>();
  61. serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessOrRequiresElevationHandler>();
  62. serviceCollection.AddSingleton<IAuthorizationHandler, RequiresElevationHandler>();
  63. serviceCollection.AddSingleton<IAuthorizationHandler, SyncPlayAccessHandler>();
  64. return serviceCollection.AddAuthorizationCore(options =>
  65. {
  66. options.AddPolicy(
  67. Policies.DefaultAuthorization,
  68. policy =>
  69. {
  70. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  71. policy.AddRequirements(new DefaultAuthorizationRequirement());
  72. });
  73. options.AddPolicy(
  74. Policies.Download,
  75. policy =>
  76. {
  77. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  78. policy.AddRequirements(new DownloadRequirement());
  79. });
  80. options.AddPolicy(
  81. Policies.FirstTimeSetupOrDefault,
  82. policy =>
  83. {
  84. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  85. policy.AddRequirements(new FirstTimeSetupOrDefaultRequirement());
  86. });
  87. options.AddPolicy(
  88. Policies.FirstTimeSetupOrElevated,
  89. policy =>
  90. {
  91. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  92. policy.AddRequirements(new FirstTimeSetupOrElevatedRequirement());
  93. });
  94. options.AddPolicy(
  95. Policies.IgnoreParentalControl,
  96. policy =>
  97. {
  98. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  99. policy.AddRequirements(new IgnoreParentalControlRequirement());
  100. });
  101. options.AddPolicy(
  102. Policies.FirstTimeSetupOrIgnoreParentalControl,
  103. policy =>
  104. {
  105. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  106. policy.AddRequirements(new FirstTimeOrIgnoreParentalControlSetupRequirement());
  107. });
  108. options.AddPolicy(
  109. Policies.LocalAccessOnly,
  110. policy =>
  111. {
  112. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  113. policy.AddRequirements(new LocalAccessRequirement());
  114. });
  115. options.AddPolicy(
  116. Policies.LocalAccessOrRequiresElevation,
  117. policy =>
  118. {
  119. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  120. policy.AddRequirements(new LocalAccessOrRequiresElevationRequirement());
  121. });
  122. options.AddPolicy(
  123. Policies.RequiresElevation,
  124. policy =>
  125. {
  126. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  127. policy.AddRequirements(new RequiresElevationRequirement());
  128. });
  129. options.AddPolicy(
  130. Policies.SyncPlayHasAccess,
  131. policy =>
  132. {
  133. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  134. policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.HasAccess));
  135. });
  136. options.AddPolicy(
  137. Policies.SyncPlayCreateGroup,
  138. policy =>
  139. {
  140. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  141. policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.CreateGroup));
  142. });
  143. options.AddPolicy(
  144. Policies.SyncPlayJoinGroup,
  145. policy =>
  146. {
  147. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  148. policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.JoinGroup));
  149. });
  150. options.AddPolicy(
  151. Policies.SyncPlayIsInGroup,
  152. policy =>
  153. {
  154. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  155. policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.IsInGroup));
  156. });
  157. });
  158. }
  159. /// <summary>
  160. /// Adds custom legacy authentication to the service collection.
  161. /// </summary>
  162. /// <param name="serviceCollection">The service collection.</param>
  163. /// <returns>The updated service collection.</returns>
  164. public static AuthenticationBuilder AddCustomAuthentication(this IServiceCollection serviceCollection)
  165. {
  166. return serviceCollection.AddAuthentication(AuthenticationSchemes.CustomAuthentication)
  167. .AddScheme<AuthenticationSchemeOptions, CustomAuthenticationHandler>(AuthenticationSchemes.CustomAuthentication, null);
  168. }
  169. /// <summary>
  170. /// Extension method for adding the jellyfin API to the service collection.
  171. /// </summary>
  172. /// <param name="serviceCollection">The service collection.</param>
  173. /// <param name="pluginAssemblies">An IEnumerable containing all plugin assemblies with API controllers.</param>
  174. /// <param name="knownProxies">A list of all known proxies to trust for X-Forwarded-For.</param>
  175. /// <returns>The MVC builder.</returns>
  176. public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable<Assembly> pluginAssemblies, IReadOnlyList<string> knownProxies)
  177. {
  178. IMvcBuilder mvcBuilder = serviceCollection
  179. .AddCors()
  180. .AddTransient<ICorsPolicyProvider, CorsPolicyProvider>()
  181. .Configure<ForwardedHeadersOptions>(options =>
  182. {
  183. options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
  184. if (knownProxies.Count == 0)
  185. {
  186. options.KnownNetworks.Clear();
  187. options.KnownProxies.Clear();
  188. }
  189. else
  190. {
  191. for (var i = 0; i < knownProxies.Count; i++)
  192. {
  193. if (IPHost.TryParse(knownProxies[i], out var host))
  194. {
  195. options.KnownProxies.Add(host.Address);
  196. }
  197. }
  198. }
  199. })
  200. .AddMvc(opts =>
  201. {
  202. // Allow requester to change between camelCase and PascalCase
  203. opts.RespectBrowserAcceptHeader = true;
  204. opts.OutputFormatters.Insert(0, new CamelCaseJsonProfileFormatter());
  205. opts.OutputFormatters.Insert(0, new PascalCaseJsonProfileFormatter());
  206. opts.OutputFormatters.Add(new CssOutputFormatter());
  207. opts.OutputFormatters.Add(new XmlOutputFormatter());
  208. opts.ModelBinderProviders.Insert(0, new NullableEnumModelBinderProvider());
  209. })
  210. // Clear app parts to avoid other assemblies being picked up
  211. .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear())
  212. .AddApplicationPart(typeof(StartupController).Assembly)
  213. .AddJsonOptions(options =>
  214. {
  215. // Update all properties that are set in JsonDefaults
  216. var jsonOptions = JsonDefaults.GetPascalCaseOptions();
  217. // From JsonDefaults
  218. options.JsonSerializerOptions.ReadCommentHandling = jsonOptions.ReadCommentHandling;
  219. options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented;
  220. options.JsonSerializerOptions.DefaultIgnoreCondition = jsonOptions.DefaultIgnoreCondition;
  221. options.JsonSerializerOptions.NumberHandling = jsonOptions.NumberHandling;
  222. options.JsonSerializerOptions.PropertyNameCaseInsensitive = jsonOptions.PropertyNameCaseInsensitive;
  223. options.JsonSerializerOptions.Converters.Clear();
  224. foreach (var converter in jsonOptions.Converters)
  225. {
  226. options.JsonSerializerOptions.Converters.Add(converter);
  227. }
  228. // From JsonDefaults.PascalCase
  229. options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy;
  230. });
  231. foreach (Assembly pluginAssembly in pluginAssemblies)
  232. {
  233. mvcBuilder.AddApplicationPart(pluginAssembly);
  234. }
  235. return mvcBuilder.AddControllersAsServices();
  236. }
  237. /// <summary>
  238. /// Adds Swagger to the service collection.
  239. /// </summary>
  240. /// <param name="serviceCollection">The service collection.</param>
  241. /// <returns>The updated service collection.</returns>
  242. public static IServiceCollection AddJellyfinApiSwagger(this IServiceCollection serviceCollection)
  243. {
  244. return serviceCollection.AddSwaggerGen(c =>
  245. {
  246. c.SwaggerDoc("api-docs", new OpenApiInfo
  247. {
  248. Title = "Jellyfin API",
  249. Version = "v1",
  250. Extensions = new Dictionary<string, IOpenApiExtension>
  251. {
  252. {
  253. "x-jellyfin-version",
  254. new OpenApiString(typeof(ApplicationHost).Assembly.GetName().Version?.ToString())
  255. }
  256. }
  257. });
  258. c.AddSecurityDefinition(AuthenticationSchemes.CustomAuthentication, new OpenApiSecurityScheme
  259. {
  260. Type = SecuritySchemeType.ApiKey,
  261. In = ParameterLocation.Header,
  262. Name = "X-Emby-Authorization",
  263. Description = "API key header parameter"
  264. });
  265. // Add all xml doc files to swagger generator.
  266. var xmlFiles = Directory.GetFiles(
  267. AppContext.BaseDirectory,
  268. "*.xml",
  269. SearchOption.TopDirectoryOnly);
  270. foreach (var xmlFile in xmlFiles)
  271. {
  272. c.IncludeXmlComments(xmlFile);
  273. }
  274. // Order actions by route path, then by http method.
  275. c.OrderActionsBy(description =>
  276. $"{description.ActionDescriptor.RouteValues["controller"]}_{description.RelativePath}");
  277. // Use method name as operationId
  278. c.CustomOperationIds(
  279. description =>
  280. {
  281. description.TryGetMethodInfo(out MethodInfo methodInfo);
  282. // Attribute name, method name, none.
  283. return description?.ActionDescriptor?.AttributeRouteInfo?.Name
  284. ?? methodInfo?.Name
  285. ?? null;
  286. });
  287. // TODO - remove when all types are supported in System.Text.Json
  288. c.AddSwaggerTypeMappings();
  289. c.OperationFilter<SecurityRequirementsOperationFilter>();
  290. c.OperationFilter<FileResponseFilter>();
  291. c.DocumentFilter<WebsocketModelFilter>();
  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. name => new OpenApiSchema
  319. {
  320. Type = "object",
  321. AdditionalProperties = new OpenApiSchema
  322. {
  323. Type = "string"
  324. }
  325. })
  326. });
  327. }
  328. }
  329. }