jellyfin/Jellyfin.Server/Extensions/ApiServiceCollectionExtensi...

389 lines
18 KiB
C#
Raw Normal View History

2020-04-19 13:24:32 -04:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
2020-05-08 10:40:37 -04:00
using System.Reflection;
2023-02-08 17:55:26 -05:00
using System.Security.Claims;
2020-11-06 15:00:14 -05:00
using Emby.Server.Implementations;
2019-11-23 13:43:30 -05:00
using Jellyfin.Api.Auth;
using Jellyfin.Api.Auth.AnonymousLanAccessPolicy;
using Jellyfin.Api.Auth.DefaultAuthorizationPolicy;
2023-02-08 17:55:26 -05:00
using Jellyfin.Api.Auth.FirstTimeSetupPolicy;
2020-08-06 10:17:45 -04:00
using Jellyfin.Api.Auth.LocalAccessOrRequiresElevationPolicy;
using Jellyfin.Api.Auth.SyncPlayAccessPolicy;
2023-02-08 17:55:26 -05:00
using Jellyfin.Api.Auth.UserPermissionPolicy;
2019-11-24 13:25:46 -05:00
using Jellyfin.Api.Constants;
2019-11-23 13:43:30 -05:00
using Jellyfin.Api.Controllers;
2023-01-13 22:23:22 -05:00
using Jellyfin.Api.Formatters;
using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Enums;
using Jellyfin.Extensions.Json;
using Jellyfin.Server.Configuration;
using Jellyfin.Server.Filters;
using MediaBrowser.Common.Api;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Session;
2019-11-23 13:43:30 -05:00
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
2020-06-17 10:05:30 -04:00
using Microsoft.AspNetCore.Builder;
2020-09-05 11:10:05 -04:00
using Microsoft.AspNetCore.Cors.Infrastructure;
2023-10-23 18:10:31 -04:00
using Microsoft.AspNetCore.HttpOverrides;
2019-11-23 13:43:30 -05:00
using Microsoft.Extensions.DependencyInjection;
2020-11-06 15:00:14 -05:00
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
2019-11-23 13:43:30 -05:00
using Microsoft.OpenApi.Models;
2020-05-08 10:40:37 -04:00
using Swashbuckle.AspNetCore.SwaggerGen;
using AuthenticationSchemes = Jellyfin.Api.Constants.AuthenticationSchemes;
2019-11-23 13:43:30 -05:00
namespace Jellyfin.Server.Extensions
2019-11-23 13:43:30 -05:00
{
2019-11-23 14:31:17 -05:00
/// <summary>
/// API specific extensions for the service collection.
/// </summary>
2019-11-23 13:43:30 -05:00
public static class ApiServiceCollectionExtensions
{
2019-11-23 14:31:17 -05: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 13:43:30 -05:00
public static IServiceCollection AddJellyfinApiAuthorization(this IServiceCollection serviceCollection)
{
2023-02-08 17:55:26 -05:00
// The default handler must be first so that it is evaluated first
serviceCollection.AddSingleton<IAuthorizationHandler, DefaultAuthorizationHandler>();
2023-02-08 17:55:26 -05:00
serviceCollection.AddSingleton<IAuthorizationHandler, UserPermissionHandler>();
serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupHandler>();
serviceCollection.AddSingleton<IAuthorizationHandler, AnonymousLanAccessHandler>();
serviceCollection.AddSingleton<IAuthorizationHandler, SyncPlayAccessHandler>();
serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessOrRequiresElevationHandler>();
2023-02-08 17:55:26 -05:00
2019-11-23 13:43:30 -05:00
return serviceCollection.AddAuthorizationCore(options =>
{
2023-02-08 17:55:26 -05:00
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication)
2023-02-09 07:15:58 -05:00
.AddRequirements(new DefaultAuthorizationRequirement())
2023-02-08 17:55:26 -05:00
.Build();
options.AddPolicy(Policies.AnonymousLanAccessPolicy, new AnonymousLanAccessRequirement());
options.AddPolicy(Policies.CollectionManagement, new UserPermissionRequirement(PermissionKind.EnableCollectionManagement));
2023-02-08 17:55:26 -05:00
options.AddPolicy(Policies.Download, new UserPermissionRequirement(PermissionKind.EnableContentDownloading));
2023-02-09 15:06:51 -05:00
options.AddPolicy(Policies.FirstTimeSetupOrDefault, new FirstTimeSetupRequirement(requireAdmin: false));
options.AddPolicy(Policies.FirstTimeSetupOrElevated, new FirstTimeSetupRequirement());
options.AddPolicy(Policies.FirstTimeSetupOrIgnoreParentalControl, new FirstTimeSetupRequirement(false, false));
2023-02-08 17:55:26 -05:00
options.AddPolicy(Policies.IgnoreParentalControl, new DefaultAuthorizationRequirement(validateParentalSchedule: false));
options.AddPolicy(Policies.LiveTvAccess, new UserPermissionRequirement(PermissionKind.EnableLiveTvAccess));
options.AddPolicy(Policies.LiveTvManagement, new UserPermissionRequirement(PermissionKind.EnableLiveTvManagement));
options.AddPolicy(Policies.LocalAccessOrRequiresElevation, new LocalAccessOrRequiresElevationRequirement());
2023-02-08 17:55:26 -05:00
options.AddPolicy(Policies.SyncPlayHasAccess, new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.HasAccess));
options.AddPolicy(Policies.SyncPlayCreateGroup, new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.CreateGroup));
options.AddPolicy(Policies.SyncPlayJoinGroup, new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.JoinGroup));
options.AddPolicy(Policies.SyncPlayIsInGroup, new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.IsInGroup));
2023-10-16 17:57:08 -04:00
options.AddPolicy(Policies.SubtitleManagement, new UserPermissionRequirement(PermissionKind.EnableSubtitleManagement));
options.AddPolicy(Policies.LyricManagement, new UserPermissionRequirement(PermissionKind.EnableLyricManagement));
options.AddPolicy(
Policies.RequiresElevation,
2023-02-08 17:55:26 -05:00
policy => policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication)
.RequireClaim(ClaimTypes.Role, UserRoles.Administrator));
2019-11-23 13:43:30 -05:00
});
}
2019-11-23 14:31:17 -05: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 13:43:30 -05:00
public static AuthenticationBuilder AddCustomAuthentication(this IServiceCollection serviceCollection)
{
2019-11-24 13:25:46 -05:00
return serviceCollection.AddAuthentication(AuthenticationSchemes.CustomAuthentication)
.AddScheme<AuthenticationSchemeOptions, CustomAuthenticationHandler>(AuthenticationSchemes.CustomAuthentication, null);
2019-11-23 13:43:30 -05:00
}
2019-11-23 14:31:17 -05:00
/// <summary>
/// Extension method for adding the Jellyfin API to the service collection.
2019-11-23 14:31:17 -05:00
/// </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 14:31:17 -05:00
/// <returns>The MVC builder.</returns>
2021-01-19 05:36:37 -05:00
public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable<Assembly> pluginAssemblies, NetworkConfiguration config)
2019-11-23 13:43:30 -05:00
{
2020-08-10 10:12:22 -04:00
IMvcBuilder mvcBuilder = serviceCollection
2021-01-12 15:43:25 -05:00
.AddCors()
.AddTransient<ICorsPolicyProvider, CorsPolicyProvider>()
.Configure<ForwardedHeadersOptions>(options =>
2020-06-17 10:05:30 -04: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 08:23:10 -05:00
options.KnownProxies.Clear();
}
else
{
2021-01-19 14:29:51 -05: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 10:05:30 -04:00
})
2020-06-01 13:03:08 -04:00
.AddMvc(opts =>
2019-11-23 13:43:30 -05:00
{
2020-08-20 13:17:27 -04:00
// Allow requester to change between camelCase and PascalCase
opts.RespectBrowserAcceptHeader = true;
2020-04-19 20:10:59 -04:00
opts.OutputFormatters.Insert(0, new CamelCaseJsonProfileFormatter());
opts.OutputFormatters.Insert(0, new PascalCaseJsonProfileFormatter());
2020-06-06 18:51:21 -04:00
opts.OutputFormatters.Add(new CssOutputFormatter());
2020-08-15 12:39:24 -04:00
opts.OutputFormatters.Add(new XmlOutputFormatter());
opts.ModelBinderProviders.Insert(0, new NullableEnumModelBinderProvider());
2019-11-23 13:43:30 -05:00
})
2019-11-23 14:31:17 -05:00
2019-11-23 13:43:30 -05: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-08 23:57:38 -05:00
var jsonOptions = JsonDefaults.PascalCaseOptions;
// From JsonDefaults
options.JsonSerializerOptions.ReadCommentHandling = jsonOptions.ReadCommentHandling;
options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented;
2020-08-25 09:33:58 -04:00
options.JsonSerializerOptions.DefaultIgnoreCondition = jsonOptions.DefaultIgnoreCondition;
2020-08-26 10:22:48 -04:00
options.JsonSerializerOptions.NumberHandling = jsonOptions.NumberHandling;
2020-08-23 09:48:12 -04: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 11:04:11 -04:00
});
2020-08-10 10:12:22 -04:00
2020-08-31 11:53:55 -04:00
foreach (Assembly pluginAssembly in pluginAssemblies)
2020-08-10 10:12:22 -04:00
{
2020-08-11 11:04:11 -04:00
mvcBuilder.AddApplicationPart(pluginAssembly);
2020-08-10 10:12:22 -04:00
}
2020-08-11 11:04:11 -04:00
return mvcBuilder.AddControllersAsServices();
2019-11-23 13:43:30 -05:00
}
2019-11-23 14:31:17 -05: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 13:43:30 -05: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 15:00:14 -05:00
c.SwaggerDoc("api-docs", new OpenApiInfo
{
Title = "Jellyfin API",
2021-03-12 19:11:43 -05:00
Version = version,
2020-11-06 15:00:14 -05:00
Extensions = new Dictionary<string, IOpenApiExtension>
{
{
"x-jellyfin-version",
2021-03-12 19:11:43 -05:00
new OpenApiString(version)
2020-11-06 15:00:14 -05:00
}
}
});
c.AddSecurityDefinition(AuthenticationSchemes.CustomAuthentication, new OpenApiSecurityScheme
{
Type = SecuritySchemeType.ApiKey,
In = ParameterLocation.Header,
Name = "Authorization",
Description = "API key header parameter"
});
2020-04-19 13:24:32 -04: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 19:44:11 -04:00
$"{description.ActionDescriptor.RouteValues["controller"]}_{description.RelativePath}");
2020-05-08 10:40:37 -04:00
// Use method name as operationId
2020-08-03 16:38:51 -04:00
c.CustomOperationIds(
description =>
{
description.TryGetMethodInfo(out MethodInfo methodInfo);
// Attribute name, method name, none.
2021-08-04 08:40:09 -04:00
return description?.ActionDescriptor.AttributeRouteInfo?.Name
2020-08-03 16:38:51 -04:00
?? methodInfo?.Name
?? null;
});
2021-01-24 16:36:36 -05:00
// Allow parameters to properly be nullable.
c.UseAllOfToExtendReferenceSchemas();
c.SupportNonNullableReferenceTypes();
2021-01-24 16:36:36 -05:00
// TODO - remove when all types are supported in System.Text.Json
c.AddSwaggerTypeMappings();
c.SchemaFilter<IgnoreEnumSchemaFilter>();
c.OperationFilter<SecurityRequirementsOperationFilter>();
c.OperationFilter<FileResponseFilter>();
2021-02-10 18:12:52 -05:00
c.OperationFilter<FileRequestFilter>();
c.OperationFilter<ParameterObsoleteFilter>();
c.DocumentFilter<AdditionalModelFilter>();
2019-11-23 13:43:30 -05:00
});
}
2023-02-08 17:55:26 -05:00
private static void AddPolicy(this AuthorizationOptions authorizationOptions, string policyName, IAuthorizationRequirement authorizationRequirement)
{
authorizationOptions.AddPolicy(policyName, policy =>
{
policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication).AddRequirements(authorizationRequirement);
});
}
2021-01-19 05:36:37 -05:00
/// <summary>
/// Sets up the proxy configuration based on the addresses/subnets in <paramref name="allowedProxies"/>.
2021-01-19 05:36:37 -05:00
/// </summary>
/// <param name="config">The <see cref="NetworkConfiguration"/> containing the config settings.</param>
2021-01-19 14:29:51 -05:00
/// <param name="allowedProxies">The string array to parse.</param>
2021-01-19 05:36:37 -05:00
/// <param name="options">The <see cref="ForwardedHeadersOptions"/> instance.</param>
2021-01-19 14:29:51 -05:00
internal static void AddProxyAddresses(NetworkConfiguration config, string[] allowedProxies, ForwardedHeadersOptions options)
2021-01-19 05:36:37 -05:00
{
2021-01-19 14:29:51 -05:00
for (var i = 0; i < allowedProxies.Length; i++)
2021-01-19 05:36:37 -05:00
{
if (IPAddress.TryParse(allowedProxies[i], out var addr))
2021-01-19 05:36:37 -05:00
{
AddIPAddress(config, options, addr, addr.AddressFamily == AddressFamily.InterNetwork ? NetworkConstants.MinimumIPv4PrefixSize : NetworkConstants.MinimumIPv6PrefixSize);
2021-01-19 05:36:37 -05:00
}
else if (NetworkUtils.TryParseToSubnet(allowedProxies[i], out var subnet))
{
if (subnet is not null)
{
AddIPAddress(config, options, subnet.Prefix, subnet.PrefixLength);
}
}
else if (NetworkUtils.TryParseHost(allowedProxies[i], out var addresses, config.EnableIPv4, config.EnableIPv6))
2021-01-19 05:36:37 -05:00
{
2022-07-21 16:09:54 -04:00
foreach (var address in addresses)
2021-01-19 05:36:37 -05:00
{
AddIPAddress(config, options, address, address.AddressFamily == AddressFamily.InterNetwork ? NetworkConstants.MinimumIPv4PrefixSize : NetworkConstants.MinimumIPv6PrefixSize);
2021-01-19 05:36:37 -05:00
}
}
}
}
2023-02-17 13:27:36 -05:00
private static void AddIPAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength)
2021-01-19 05:36:37 -05:00
{
2023-07-03 15:51:36 -04:00
if (addr.IsIPv4MappedToIPv6)
2021-01-19 05:36:37 -05:00
{
2023-07-03 15:51:36 -04:00
addr = addr.MapToIPv4();
2021-01-19 05:36:37 -05:00
}
2023-07-03 15:51:36 -04:00
if ((!config.EnableIPv4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPv6 && addr.AddressFamily == AddressFamily.InterNetworkV6))
2022-07-20 05:47:48 -04:00
{
2023-07-03 15:51:36 -04:00
return;
2022-07-20 05:47:48 -04:00
}
if (prefixLength == NetworkConstants.MinimumIPv4PrefixSize)
2021-01-19 05:36:37 -05:00
{
options.KnownProxies.Add(addr);
}
else
{
2023-10-23 18:10:31 -04:00
options.KnownNetworks.Add(new Microsoft.AspNetCore.HttpOverrides.IPNetwork(addr, prefixLength));
2021-01-19 05:36:37 -05:00
}
}
private static void AddSwaggerTypeMappings(this SwaggerGenOptions options)
{
/*
2020-11-30 10:47:52 -05: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 10:47:52 -05:00
AdditionalProperties = new OpenApiSchema
{
Type = "string"
}
});
2020-06-19 09:49:44 -04: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 08:40:09 -04:00
_ => new OpenApiSchema
{
2020-11-30 10:47:52 -05:00
Type = "object",
AdditionalProperties = new OpenApiSchema
2020-06-19 09:49:44 -04:00
{
2020-11-30 10:47:52 -05:00
Type = "string"
2020-06-19 09:49:44 -04:00
}
})
});
// Support dictionary with nullable string value.
options.MapType<Dictionary<string, string?>>(() =>
new OpenApiSchema
{
Type = "object",
AdditionalProperties = new OpenApiSchema
{
Type = "string",
Nullable = true
}
});
// Manually describe Flags enum.
options.MapType<TranscodeReason>(() =>
new OpenApiSchema
{
Type = "array",
Items = new OpenApiSchema
{
Reference = new OpenApiReference
{
Id = nameof(TranscodeReason),
Type = ReferenceType.Schema,
}
}
});
// Swashbuckle doesn't use JsonOptions to describe responses, so we need to manually describe it.
options.MapType<Version>(() => new OpenApiSchema
{
Type = "string"
});
}
2019-11-23 13:43:30 -05:00
}
}