jellyfin-server/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs

434 lines
20 KiB
C#
Raw Normal View History

2020-04-19 17:24:32 +00:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
2020-05-08 14:40:37 +00:00
using System.Reflection;
2020-11-06 20:00:14 +00:00
using Emby.Server.Implementations;
2019-11-23 18:43:30 +00:00
using Jellyfin.Api.Auth;
using Jellyfin.Api.Auth.AnonymousLanAccessPolicy;
using Jellyfin.Api.Auth.DefaultAuthorizationPolicy;
2020-06-19 19:10:10 +00:00
using Jellyfin.Api.Auth.DownloadPolicy;
2020-08-06 23:59:48 +00:00
using Jellyfin.Api.Auth.FirstTimeOrIgnoreParentalControlSetupPolicy;
2020-08-06 14:17:45 +00:00
using Jellyfin.Api.Auth.FirstTimeSetupOrDefaultPolicy;
2019-11-23 18:43:30 +00:00
using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy;
2020-08-06 14:17:45 +00:00
using Jellyfin.Api.Auth.IgnoreParentalControlPolicy;
using Jellyfin.Api.Auth.LocalAccessOrRequiresElevationPolicy;
using Jellyfin.Api.Auth.LocalAccessPolicy;
2019-11-23 18:43:30 +00:00
using Jellyfin.Api.Auth.RequiresElevationPolicy;
using Jellyfin.Api.Auth.SyncPlayAccessPolicy;
2019-11-24 18:25:46 +00:00
using Jellyfin.Api.Constants;
2019-11-23 18:43:30 +00:00
using Jellyfin.Api.Controllers;
using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Enums;
using Jellyfin.Extensions.Json;
using Jellyfin.Networking.Configuration;
using Jellyfin.Server.Configuration;
using Jellyfin.Server.Filters;
2020-04-20 00:10:59 +00:00
using Jellyfin.Server.Formatters;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Entities;
2019-11-23 18:43:30 +00:00
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
2020-06-17 14:05:30 +00:00
using Microsoft.AspNetCore.Builder;
2020-09-05 15:10:05 +00:00
using Microsoft.AspNetCore.Cors.Infrastructure;
2020-06-17 14:05:30 +00:00
using Microsoft.AspNetCore.HttpOverrides;
2019-11-23 18:43:30 +00:00
using Microsoft.Extensions.DependencyInjection;
2020-11-06 20:00:14 +00:00
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
2019-11-23 18:43:30 +00:00
using Microsoft.OpenApi.Models;
2020-05-08 14:40:37 +00:00
using Swashbuckle.AspNetCore.SwaggerGen;
using AuthenticationSchemes = Jellyfin.Api.Constants.AuthenticationSchemes;
2019-11-23 18:43:30 +00:00
namespace Jellyfin.Server.Extensions
2019-11-23 18:43:30 +00:00
{
2019-11-23 19:31:17 +00:00
/// <summary>
/// API specific extensions for the service collection.
/// </summary>
2019-11-23 18:43:30 +00:00
public static class ApiServiceCollectionExtensions
{
2019-11-23 19:31:17 +00:00
/// <summary>
/// Adds jellyfin API authorization policies to the DI container.
/// </summary>
/// <param name="serviceCollection">The service collection.</param>
/// <returns>The updated service collection.</returns>
2019-11-23 18:43:30 +00:00
public static IServiceCollection AddJellyfinApiAuthorization(this IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<IAuthorizationHandler, DefaultAuthorizationHandler>();
2020-06-19 19:10:10 +00:00
serviceCollection.AddSingleton<IAuthorizationHandler, DownloadHandler>();
2020-08-06 14:17:45 +00:00
serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrDefaultHandler>();
2019-11-23 18:43:30 +00:00
serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrElevatedHandler>();
2020-08-06 14:17:45 +00:00
serviceCollection.AddSingleton<IAuthorizationHandler, IgnoreParentalControlHandler>();
2020-08-06 23:59:48 +00:00
serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeOrIgnoreParentalControlSetupHandler>();
serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessHandler>();
serviceCollection.AddSingleton<IAuthorizationHandler, AnonymousLanAccessHandler>();
2020-08-06 14:17:45 +00:00
serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessOrRequiresElevationHandler>();
2019-11-23 18:43:30 +00:00
serviceCollection.AddSingleton<IAuthorizationHandler, RequiresElevationHandler>();
serviceCollection.AddSingleton<IAuthorizationHandler, SyncPlayAccessHandler>();
2019-11-23 18:43:30 +00:00
return serviceCollection.AddAuthorizationCore(options =>
{
options.AddPolicy(
Policies.DefaultAuthorization,
2019-11-23 18:43:30 +00:00
policy =>
{
2019-11-24 18:25:46 +00:00
policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
policy.AddRequirements(new DefaultAuthorizationRequirement());
2019-11-23 18:43:30 +00:00
});
2020-06-19 19:10:10 +00:00
options.AddPolicy(
Policies.Download,
policy =>
{
policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
policy.AddRequirements(new DownloadRequirement());
});
2020-08-06 14:17:45 +00:00
options.AddPolicy(
Policies.FirstTimeSetupOrDefault,
policy =>
{
policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
policy.AddRequirements(new FirstTimeSetupOrDefaultRequirement());
});
2019-11-23 18:43:30 +00:00
options.AddPolicy(
2019-11-24 18:25:46 +00:00
Policies.FirstTimeSetupOrElevated,
2019-11-23 18:43:30 +00:00
policy =>
{
2019-11-24 18:25:46 +00:00
policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
2019-11-23 18:43:30 +00:00
policy.AddRequirements(new FirstTimeSetupOrElevatedRequirement());
});
options.AddPolicy(
2020-08-06 14:17:45 +00:00
Policies.IgnoreParentalControl,
policy =>
{
policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
2020-08-06 14:17:45 +00:00
policy.AddRequirements(new IgnoreParentalControlRequirement());
});
options.AddPolicy(
2020-08-06 23:59:48 +00:00
Policies.FirstTimeSetupOrIgnoreParentalControl,
2020-08-06 14:17:45 +00:00
policy =>
{
policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
2020-08-06 23:59:48 +00:00
policy.AddRequirements(new FirstTimeOrIgnoreParentalControlSetupRequirement());
});
options.AddPolicy(
Policies.LocalAccessOnly,
policy =>
{
policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
policy.AddRequirements(new LocalAccessRequirement());
});
2020-08-06 14:17:45 +00:00
options.AddPolicy(
Policies.LocalAccessOrRequiresElevation,
policy =>
{
policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
policy.AddRequirements(new LocalAccessOrRequiresElevationRequirement());
});
options.AddPolicy(
Policies.RequiresElevation,
policy =>
{
policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
policy.AddRequirements(new RequiresElevationRequirement());
});
options.AddPolicy(
Policies.SyncPlayHasAccess,
policy =>
{
policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.HasAccess));
});
options.AddPolicy(
Policies.SyncPlayCreateGroup,
policy =>
{
policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.CreateGroup));
});
options.AddPolicy(
Policies.SyncPlayJoinGroup,
policy =>
{
policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.JoinGroup));
});
options.AddPolicy(
Policies.SyncPlayIsInGroup,
policy =>
{
policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.IsInGroup));
});
2021-04-10 11:03:52 +00:00
options.AddPolicy(
Policies.AnonymousLanAccessPolicy,
2021-04-10 11:03:52 +00:00
policy =>
{
policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
policy.AddRequirements(new AnonymousLanAccessRequirement());
2021-04-10 11:03:52 +00:00
});
2019-11-23 18:43:30 +00:00
});
}
2019-11-23 19:31:17 +00:00
/// <summary>
/// Adds custom legacy authentication to the service collection.
/// </summary>
/// <param name="serviceCollection">The service collection.</param>
/// <returns>The updated service collection.</returns>
2019-11-23 18:43:30 +00:00
public static AuthenticationBuilder AddCustomAuthentication(this IServiceCollection serviceCollection)
{
2019-11-24 18:25:46 +00:00
return serviceCollection.AddAuthentication(AuthenticationSchemes.CustomAuthentication)
.AddScheme<AuthenticationSchemeOptions, CustomAuthenticationHandler>(AuthenticationSchemes.CustomAuthentication, null);
2019-11-23 18:43:30 +00:00
}
2019-11-23 19:31:17 +00:00
/// <summary>
/// Extension method for adding the jellyfin API to the service collection.
/// </summary>
/// <param name="serviceCollection">The service collection.</param>
/// <param name="pluginAssemblies">An IEnumerable containing all plugin assemblies with API controllers.</param>
/// <param name="config">The <see cref="NetworkConfiguration"/>.</param>
2019-11-23 19:31:17 +00:00
/// <returns>The MVC builder.</returns>
2021-01-19 10:36:37 +00:00
public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable<Assembly> pluginAssemblies, NetworkConfiguration config)
2019-11-23 18:43:30 +00:00
{
2020-08-10 14:12:22 +00:00
IMvcBuilder mvcBuilder = serviceCollection
2021-01-12 20:43:25 +00:00
.AddCors()
.AddTransient<ICorsPolicyProvider, CorsPolicyProvider>()
.Configure<ForwardedHeadersOptions>(options =>
2020-06-17 14:05:30 +00:00
{
// https://github.com/dotnet/aspnetcore/blob/master/src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs
// Enable debug logging on Microsoft.AspNetCore.HttpOverrides.ForwardedHeadersMiddleware to help investigate issues.
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
if (config.KnownProxies.Length == 0)
{
options.KnownNetworks.Clear();
2021-01-12 13:23:10 +00:00
options.KnownProxies.Clear();
}
else
{
2021-01-19 19:29:51 +00:00
AddProxyAddresses(config, config.KnownProxies, options);
}
// Only set forward limit if we have some known proxies or some known networks.
if (options.KnownProxies.Count != 0 || options.KnownNetworks.Count != 0)
{
options.ForwardLimit = null;
}
2020-06-17 14:05:30 +00:00
})
2020-06-01 17:03:08 +00:00
.AddMvc(opts =>
2019-11-23 18:43:30 +00:00
{
2020-08-20 17:17:27 +00:00
// Allow requester to change between camelCase and PascalCase
opts.RespectBrowserAcceptHeader = true;
2020-04-20 00:10:59 +00:00
opts.OutputFormatters.Insert(0, new CamelCaseJsonProfileFormatter());
opts.OutputFormatters.Insert(0, new PascalCaseJsonProfileFormatter());
2020-06-06 22:51:21 +00:00
opts.OutputFormatters.Add(new CssOutputFormatter());
2020-08-15 16:39:24 +00:00
opts.OutputFormatters.Add(new XmlOutputFormatter());
opts.ModelBinderProviders.Insert(0, new NullableEnumModelBinderProvider());
2019-11-23 18:43:30 +00:00
})
2019-11-23 19:31:17 +00:00
2019-11-23 18:43:30 +00:00
// Clear app parts to avoid other assemblies being picked up
.ConfigureApplicationPartManager(a => a.ApplicationParts.Clear())
.AddApplicationPart(typeof(StartupController).Assembly)
.AddJsonOptions(options =>
{
// Update all properties that are set in JsonDefaults
2021-03-09 04:57:38 +00:00
var jsonOptions = JsonDefaults.PascalCaseOptions;
// From JsonDefaults
options.JsonSerializerOptions.ReadCommentHandling = jsonOptions.ReadCommentHandling;
options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented;
2020-08-25 13:33:58 +00:00
options.JsonSerializerOptions.DefaultIgnoreCondition = jsonOptions.DefaultIgnoreCondition;
2020-08-26 14:22:48 +00:00
options.JsonSerializerOptions.NumberHandling = jsonOptions.NumberHandling;
2020-08-23 13:48:12 +00:00
options.JsonSerializerOptions.Converters.Clear();
foreach (var converter in jsonOptions.Converters)
{
options.JsonSerializerOptions.Converters.Add(converter);
}
// From JsonDefaults.PascalCase
options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy;
2020-08-11 15:04:11 +00:00
});
2020-08-10 14:12:22 +00:00
2020-08-31 15:53:55 +00:00
foreach (Assembly pluginAssembly in pluginAssemblies)
2020-08-10 14:12:22 +00:00
{
2020-08-11 15:04:11 +00:00
mvcBuilder.AddApplicationPart(pluginAssembly);
2020-08-10 14:12:22 +00:00
}
2020-08-11 15:04:11 +00:00
return mvcBuilder.AddControllersAsServices();
2019-11-23 18:43:30 +00:00
}
2019-11-23 19:31:17 +00:00
/// <summary>
/// Adds Swagger to the service collection.
/// </summary>
/// <param name="serviceCollection">The service collection.</param>
/// <returns>The updated service collection.</returns>
2019-11-23 18:43:30 +00:00
public static IServiceCollection AddJellyfinApiSwagger(this IServiceCollection serviceCollection)
{
return serviceCollection.AddSwaggerGen(c =>
{
var version = typeof(ApplicationHost).Assembly.GetName().Version?.ToString(3) ?? "0.0.1";
2020-11-06 20:00:14 +00:00
c.SwaggerDoc("api-docs", new OpenApiInfo
{
Title = "Jellyfin API",
2021-03-13 00:11:43 +00:00
Version = version,
2020-11-06 20:00:14 +00:00
Extensions = new Dictionary<string, IOpenApiExtension>
{
{
"x-jellyfin-version",
2021-03-13 00:11:43 +00:00
new OpenApiString(version)
2020-11-06 20:00:14 +00:00
}
}
});
c.AddSecurityDefinition(AuthenticationSchemes.CustomAuthentication, new OpenApiSecurityScheme
{
Type = SecuritySchemeType.ApiKey,
In = ParameterLocation.Header,
Name = "Authorization",
Description = "API key header parameter"
});
2020-04-19 17:24:32 +00:00
// Add all xml doc files to swagger generator.
var xmlFiles = Directory.GetFiles(
AppContext.BaseDirectory,
"*.xml",
SearchOption.TopDirectoryOnly);
foreach (var xmlFile in xmlFiles)
{
c.IncludeXmlComments(xmlFile);
}
// Order actions by route path, then by http method.
c.OrderActionsBy(description =>
2020-06-25 23:44:11 +00:00
$"{description.ActionDescriptor.RouteValues["controller"]}_{description.RelativePath}");
2020-05-08 14:40:37 +00:00
// Use method name as operationId
2020-08-03 20:38:51 +00:00
c.CustomOperationIds(
description =>
{
description.TryGetMethodInfo(out MethodInfo methodInfo);
// Attribute name, method name, none.
2021-08-04 12:40:09 +00:00
return description?.ActionDescriptor.AttributeRouteInfo?.Name
2020-08-03 20:38:51 +00:00
?? methodInfo?.Name
?? null;
});
2021-01-24 21:36:36 +00:00
// Allow parameters to properly be nullable.
c.UseAllOfToExtendReferenceSchemas();
c.SupportNonNullableReferenceTypes();
2021-01-24 21:36:36 +00:00
// TODO - remove when all types are supported in System.Text.Json
c.AddSwaggerTypeMappings();
c.OperationFilter<SecurityRequirementsOperationFilter>();
c.OperationFilter<FileResponseFilter>();
2021-02-10 23:12:52 +00:00
c.OperationFilter<FileRequestFilter>();
c.OperationFilter<ParameterObsoleteFilter>();
c.DocumentFilter<AdditionalModelFilter>();
2019-11-23 18:43:30 +00:00
});
}
2021-01-19 10:36:37 +00:00
/// <summary>
2021-01-19 19:29:51 +00:00
/// Sets up the proxy configuration based on the addresses in <paramref name="allowedProxies"/>.
2021-01-19 10:36:37 +00:00
/// </summary>
/// <param name="config">The <see cref="NetworkConfiguration"/> containing the config settings.</param>
2021-01-19 19:29:51 +00:00
/// <param name="allowedProxies">The string array to parse.</param>
2021-01-19 10:36:37 +00:00
/// <param name="options">The <see cref="ForwardedHeadersOptions"/> instance.</param>
2021-01-19 19:29:51 +00:00
internal static void AddProxyAddresses(NetworkConfiguration config, string[] allowedProxies, ForwardedHeadersOptions options)
2021-01-19 10:36:37 +00:00
{
2021-01-19 19:29:51 +00:00
for (var i = 0; i < allowedProxies.Length; i++)
2021-01-19 10:36:37 +00:00
{
2021-01-19 19:29:51 +00:00
if (IPNetAddress.TryParse(allowedProxies[i], out var addr))
2021-01-19 10:36:37 +00:00
{
AddIpAddress(config, options, addr.Address, addr.PrefixLength);
}
2021-01-19 19:29:51 +00:00
else if (IPHost.TryParse(allowedProxies[i], out var host))
2021-01-19 10:36:37 +00:00
{
foreach (var address in host.GetAddresses())
{
2021-08-04 12:40:09 +00:00
AddIpAddress(config, options, address, address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128);
2021-01-19 10:36:37 +00:00
}
}
}
}
private static void AddIpAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength)
{
if ((!config.EnableIPV4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPV6 && addr.AddressFamily == AddressFamily.InterNetworkV6))
{
return;
}
2021-01-19 11:31:40 +00:00
// 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.
2021-01-19 12:50:11 +00:00
if (addr.AddressFamily == AddressFamily.InterNetwork && config.EnableIPV6)
2021-01-19 10:36:37 +00:00
{
// If the server is using dual-mode sockets, IPv4 addresses are supplied in an IPv6 format.
// https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0 .
addr = addr.MapToIPv6();
}
if (prefixLength == 32)
{
options.KnownProxies.Add(addr);
}
else
{
options.KnownNetworks.Add(new IPNetwork(addr, prefixLength));
}
}
private static void AddSwaggerTypeMappings(this SwaggerGenOptions options)
{
/*
2020-11-30 15:47:52 +00:00
* TODO remove when System.Text.Json properly supports non-string keys.
* Used in BaseItemDto.ImageBlurHashes
*/
options.MapType<Dictionary<ImageType, string>>(() =>
new OpenApiSchema
{
Type = "object",
2020-11-30 15:47:52 +00:00
AdditionalProperties = new OpenApiSchema
{
Type = "string"
}
});
2020-06-19 13:49:44 +00:00
/*
* Support BlurHash dictionary
*/
options.MapType<Dictionary<ImageType, Dictionary<string, string>>>(() =>
new OpenApiSchema
{
Type = "object",
Properties = typeof(ImageType).GetEnumNames().ToDictionary(
name => name,
2021-08-04 12:40:09 +00:00
_ => new OpenApiSchema
{
2020-11-30 15:47:52 +00:00
Type = "object",
AdditionalProperties = new OpenApiSchema
2020-06-19 13:49:44 +00:00
{
2020-11-30 15:47:52 +00:00
Type = "string"
2020-06-19 13:49:44 +00:00
}
})
});
// Support dictionary with nullable string value.
options.MapType<Dictionary<string, string?>>(() =>
new OpenApiSchema
{
Type = "object",
AdditionalProperties = new OpenApiSchema
{
Type = "string",
Nullable = true
}
});
}
2019-11-23 18:43:30 +00:00
}
}