< Summary - Jellyfin

Information
Class: Jellyfin.Server.Extensions.ApiServiceCollectionExtensions
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
Line coverage
96%
Covered lines: 208
Uncovered lines: 7
Coverable lines: 215
Total lines: 373
Line coverage: 96.7%
Branch coverage
80%
Covered branches: 32
Total branches: 40
Branch coverage: 80%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 6/7/2026 - 12:16:09 AM Line coverage: 96.5% (198/205) Branch coverage: 80% (32/40) Total lines: 35911/27/2026 - 12:22:30 AM Line coverage: 96.7% (208/215) Branch coverage: 80% (32/40) Total lines: 373 6/7/2026 - 12:16:09 AM Line coverage: 96.5% (198/205) Branch coverage: 80% (32/40) Total lines: 35911/27/2026 - 12:22:30 AM Line coverage: 96.7% (208/215) Branch coverage: 80% (32/40) Total lines: 373

Coverage delta

Coverage delta 1 -1

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
AddJellyfinApiAuthorization(...)100%11100%
AddCustomAuthentication(...)100%11100%
AddJellyfinApi(...)100%22100%
ConfigureForwardHeaders(...)50%7666.66%
AddJellyfinApiSwagger(...)100%11100%
AddPolicy(...)100%11100%
AddProxyAddresses(...)92.85%141488.88%
AddIPAddress(...)77.77%351862.5%
AddSwaggerTypeMappings(...)100%11100%

File(s)

/srv/git/jellyfin/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using System.Net;
 5using System.Net.Sockets;
 6using System.Reflection;
 7using System.Security.Claims;
 8using System.Text.Json.Nodes;
 9using System.Text.Json.Serialization.Metadata;
 10using Emby.Server.Implementations;
 11using Jellyfin.Api.Auth;
 12using Jellyfin.Api.Auth.AnonymousLanAccessPolicy;
 13using Jellyfin.Api.Auth.DefaultAuthorizationPolicy;
 14using Jellyfin.Api.Auth.FirstTimeSetupPolicy;
 15using Jellyfin.Api.Auth.LocalAccessOrRequiresElevationPolicy;
 16using Jellyfin.Api.Auth.SyncPlayAccessPolicy;
 17using Jellyfin.Api.Auth.UserPermissionPolicy;
 18using Jellyfin.Api.Constants;
 19using Jellyfin.Api.Controllers;
 20using Jellyfin.Api.Formatters;
 21using Jellyfin.Api.Helpers;
 22using Jellyfin.Api.ModelBinders;
 23using Jellyfin.Data.Enums;
 24using Jellyfin.Database.Implementations.Enums;
 25using Jellyfin.Extensions.Json;
 26using Jellyfin.Server.Configuration;
 27using Jellyfin.Server.Filters;
 28using MediaBrowser.Common.Api;
 29using MediaBrowser.Common.Net;
 30using MediaBrowser.Model.Configuration;
 31using MediaBrowser.Model.Entities;
 32using Microsoft.AspNetCore.Authentication;
 33using Microsoft.AspNetCore.Authorization;
 34using Microsoft.AspNetCore.Builder;
 35using Microsoft.AspNetCore.Cors.Infrastructure;
 36using Microsoft.AspNetCore.HttpOverrides;
 37using Microsoft.Extensions.DependencyInjection;
 38using Microsoft.Extensions.DependencyInjection.Extensions;
 39using Microsoft.OpenApi;
 40using Swashbuckle.AspNetCore.Swagger;
 41using Swashbuckle.AspNetCore.SwaggerGen;
 42using AuthenticationSchemes = Jellyfin.Api.Constants.AuthenticationSchemes;
 43
 44namespace Jellyfin.Server.Extensions
 45{
 46    /// <summary>
 47    /// API specific extensions for the service collection.
 48    /// </summary>
 49    public static class ApiServiceCollectionExtensions
 50    {
 51        /// <summary>
 52        /// Adds jellyfin API authorization policies to the DI container.
 53        /// </summary>
 54        /// <param name="serviceCollection">The service collection.</param>
 55        /// <returns>The updated service collection.</returns>
 56        public static IServiceCollection AddJellyfinApiAuthorization(this IServiceCollection serviceCollection)
 57        {
 58            // The default handler must be first so that it is evaluated first
 3159            serviceCollection.AddSingleton<IAuthorizationHandler, DefaultAuthorizationHandler>();
 3160            serviceCollection.AddSingleton<IAuthorizationHandler, UserPermissionHandler>();
 3161            serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupHandler>();
 3162            serviceCollection.AddSingleton<IAuthorizationHandler, AnonymousLanAccessHandler>();
 3163            serviceCollection.AddSingleton<IAuthorizationHandler, SyncPlayAccessHandler>();
 3164            serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessOrRequiresElevationHandler>();
 65
 3166            return serviceCollection.AddAuthorizationCore(options =>
 3167            {
 3168                options.DefaultPolicy = new AuthorizationPolicyBuilder()
 3169                    .AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication)
 3170                    .AddRequirements(new DefaultAuthorizationRequirement())
 3171                    .Build();
 3172
 3173                options.AddPolicy(Policies.AnonymousLanAccessPolicy, new AnonymousLanAccessRequirement());
 3174                options.AddPolicy(Policies.CollectionManagement, new UserPermissionRequirement(PermissionKind.EnableColl
 3175                options.AddPolicy(Policies.Download, new UserPermissionRequirement(PermissionKind.EnableContentDownloadi
 3176                options.AddPolicy(Policies.FirstTimeSetupOrDefault, new FirstTimeSetupRequirement(requireAdmin: false));
 3177                options.AddPolicy(Policies.FirstTimeSetupOrElevated, new FirstTimeSetupRequirement());
 3178                options.AddPolicy(Policies.FirstTimeSetupOrIgnoreParentalControl, new FirstTimeSetupRequirement(false, f
 3179                options.AddPolicy(Policies.IgnoreParentalControl, new DefaultAuthorizationRequirement(validateParentalSc
 3180                options.AddPolicy(Policies.LiveTvAccess, new UserPermissionRequirement(PermissionKind.EnableLiveTvAccess
 3181                options.AddPolicy(Policies.LiveTvManagement, new UserPermissionRequirement(PermissionKind.EnableLiveTvMa
 3182                options.AddPolicy(Policies.LocalAccessOrRequiresElevation, new LocalAccessOrRequiresElevationRequirement
 3183                options.AddPolicy(Policies.SyncPlayHasAccess, new SyncPlayAccessRequirement(SyncPlayAccessRequirementTyp
 3184                options.AddPolicy(Policies.SyncPlayCreateGroup, new SyncPlayAccessRequirement(SyncPlayAccessRequirementT
 3185                options.AddPolicy(Policies.SyncPlayJoinGroup, new SyncPlayAccessRequirement(SyncPlayAccessRequirementTyp
 3186                options.AddPolicy(Policies.SyncPlayIsInGroup, new SyncPlayAccessRequirement(SyncPlayAccessRequirementTyp
 3187                options.AddPolicy(Policies.SubtitleManagement, new UserPermissionRequirement(PermissionKind.EnableSubtit
 3188                options.AddPolicy(Policies.LyricManagement, new UserPermissionRequirement(PermissionKind.EnableLyricMana
 3189                options.AddPolicy(
 3190                    Policies.RequiresElevation,
 3191                    policy => policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication)
 3192                        .RequireClaim(ClaimTypes.Role, UserRoles.Administrator));
 3193            });
 94        }
 95
 96        /// <summary>
 97        /// Adds custom legacy authentication to the service collection.
 98        /// </summary>
 99        /// <param name="serviceCollection">The service collection.</param>
 100        /// <returns>The updated service collection.</returns>
 101        public static AuthenticationBuilder AddCustomAuthentication(this IServiceCollection serviceCollection)
 102        {
 31103            return serviceCollection.AddAuthentication(AuthenticationSchemes.CustomAuthentication)
 31104                .AddScheme<AuthenticationSchemeOptions, CustomAuthenticationHandler>(AuthenticationSchemes.CustomAuthent
 105        }
 106
 107        /// <summary>
 108        /// Extension method for adding the Jellyfin API to the service collection.
 109        /// </summary>
 110        /// <param name="serviceCollection">The service collection.</param>
 111        /// <param name="pluginAssemblies">An IEnumerable containing all plugin assemblies with API controllers.</param>
 112        /// <param name="config">The <see cref="NetworkConfiguration"/>.</param>
 113        /// <param name="serverConfiguration">The <see cref="ServerConfiguration"/>.</param>
 114        /// <returns>The MVC builder.</returns>
 115        public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable<Assembly> plugin
 116        {
 31117            IMvcBuilder mvcBuilder = serviceCollection
 31118                .AddCors()
 31119                .AddTransient<ICorsPolicyProvider, CorsPolicyProvider>()
 31120                .Configure<ForwardedHeadersOptions>(options =>
 31121                {
 31122                    ConfigureForwardHeaders(config, options);
 31123                })
 31124                .AddMvc(opts =>
 31125                {
 31126                    // Allow requester to change between camelCase and PascalCase
 31127                    opts.RespectBrowserAcceptHeader = true;
 31128
 31129                    opts.OutputFormatters.Insert(0, new CamelCaseJsonProfileFormatter());
 31130                    opts.OutputFormatters.Insert(0, new PascalCaseJsonProfileFormatter());
 31131
 31132                    opts.OutputFormatters.Add(new CssOutputFormatter());
 31133                    opts.OutputFormatters.Add(new XmlOutputFormatter());
 31134
 31135                    opts.ModelBinderProviders.Insert(0, new NullableEnumModelBinderProvider());
 31136
 31137                    if (!serverConfiguration.EnableObsoleteEndpoints)
 31138                    {
 31139                        opts.Conventions.Add(new ObsoleteEndpointConvention());
 31140                    }
 31141                })
 31142
 31143                // Clear app parts to avoid other assemblies being picked up
 31144                .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear())
 31145                .AddApplicationPart(typeof(StartupController).Assembly)
 31146                .AddJsonOptions(options =>
 31147                {
 31148                    // Update all properties that are set in JsonDefaults
 31149                    var jsonOptions = JsonDefaults.PascalCaseOptions;
 31150
 31151                    // From JsonDefaults
 31152                    options.JsonSerializerOptions.ReadCommentHandling = jsonOptions.ReadCommentHandling;
 31153                    options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented;
 31154                    options.JsonSerializerOptions.DefaultIgnoreCondition = jsonOptions.DefaultIgnoreCondition;
 31155                    options.JsonSerializerOptions.NumberHandling = jsonOptions.NumberHandling;
 31156
 31157                    options.JsonSerializerOptions.Converters.Clear();
 31158                    foreach (var converter in jsonOptions.Converters)
 31159                    {
 31160                        options.JsonSerializerOptions.Converters.Add(converter);
 31161                    }
 31162
 31163                    // From JsonDefaults.PascalCase
 31164                    options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy;
 31165
 31166                    options.JsonSerializerOptions.TypeInfoResolver = new DefaultJsonTypeInfoResolver
 31167                    {
 31168                        Modifiers = { ConfigurationJsonTypeInfoModifier.Modify }
 31169                    };
 31170                });
 171
 186172            foreach (Assembly pluginAssembly in pluginAssemblies)
 173            {
 62174                mvcBuilder.AddApplicationPart(pluginAssembly);
 175            }
 176
 31177            return mvcBuilder.AddControllersAsServices();
 178        }
 179
 180        internal static void ConfigureForwardHeaders(NetworkConfiguration config, ForwardedHeadersOptions options)
 181        {
 182            // https://github.com/dotnet/aspnetcore/blob/master/src/Middleware/HttpOverrides/src/ForwardedHeadersMiddlew
 183            // Enable debug logging on Microsoft.AspNetCore.HttpOverrides.ForwardedHeadersMiddleware to help investigate
 184
 30185            if (config.KnownProxies.Length == 0)
 186            {
 30187                options.ForwardedHeaders = ForwardedHeaders.None;
 30188                options.KnownIPNetworks.Clear();
 30189                options.KnownProxies.Clear();
 190            }
 191            else
 192            {
 0193                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | Forwarded
 0194                AddProxyAddresses(config, config.KnownProxies, options);
 195            }
 196
 197            // Only set forward limit if we have some known proxies or some known networks.
 30198            if (options.KnownProxies.Count != 0 || options.KnownIPNetworks.Count != 0)
 199            {
 0200                options.ForwardLimit = null;
 201            }
 30202        }
 203
 204        /// <summary>
 205        /// Adds Swagger to the service collection.
 206        /// </summary>
 207        /// <param name="serviceCollection">The service collection.</param>
 208        /// <returns>The updated service collection.</returns>
 209        public static IServiceCollection AddJellyfinApiSwagger(this IServiceCollection serviceCollection)
 210        {
 31211            return serviceCollection.AddSwaggerGen(c =>
 31212            {
 31213                var version = typeof(ApplicationHost).Assembly.GetName().Version?.ToString(3) ?? "0.0.1";
 31214                c.SwaggerDoc("api-docs", new OpenApiInfo
 31215                {
 31216                    Title = "Jellyfin API",
 31217                    Version = version,
 31218                    Extensions = new Dictionary<string, IOpenApiExtension>
 31219                    {
 31220                        {
 31221                            "x-jellyfin-version",
 31222                            new JsonNodeExtension(JsonValue.Create(version))
 31223                        }
 31224                    }
 31225                });
 31226
 31227                c.AddSecurityDefinition(AuthenticationSchemes.CustomAuthentication, new OpenApiSecurityScheme
 31228                {
 31229                    Type = SecuritySchemeType.ApiKey,
 31230                    In = ParameterLocation.Header,
 31231                    Name = "Authorization",
 31232                    Description = "API key header parameter"
 31233                });
 31234
 31235                // Add all xml doc files to swagger generator.
 31236                var xmlFiles = Directory.EnumerateFiles(
 31237                    AppContext.BaseDirectory,
 31238                    "*.xml",
 31239                    SearchOption.TopDirectoryOnly);
 31240
 31241                foreach (var xmlFile in xmlFiles)
 31242                {
 31243                    c.IncludeXmlComments(xmlFile);
 31244                }
 31245
 31246                // Order actions by route path, then by http method.
 31247                c.OrderActionsBy(description =>
 31248                    $"{description.ActionDescriptor.RouteValues["controller"]}_{description.RelativePath}");
 31249
 31250                // Use method name as operationId
 31251                c.CustomOperationIds(
 31252                    description =>
 31253                    {
 31254                        description.TryGetMethodInfo(out MethodInfo methodInfo);
 31255                        // Attribute name, method name, none.
 31256                        return description?.ActionDescriptor.AttributeRouteInfo?.Name
 31257                               ?? methodInfo?.Name
 31258                               ?? null;
 31259                    });
 31260
 31261                // Allow parameters to properly be nullable.
 31262                c.UseAllOfToExtendReferenceSchemas();
 31263                c.SupportNonNullableReferenceTypes();
 31264
 31265                // TODO - remove when all types are supported in System.Text.Json
 31266                c.AddSwaggerTypeMappings();
 31267
 31268                c.SchemaFilter<IgnoreEnumSchemaFilter>();
 31269                c.SchemaFilter<FlagsEnumSchemaFilter>();
 31270                c.OperationFilter<RetryOnTemporarilyUnavailableFilter>();
 31271                c.OperationFilter<SecurityRequirementsOperationFilter>();
 31272                c.OperationFilter<FileResponseFilter>();
 31273                c.OperationFilter<FileRequestFilter>();
 31274                c.OperationFilter<ParameterObsoleteFilter>();
 31275                c.DocumentFilter<AdditionalModelFilter>();
 31276                c.DocumentFilter<SecuritySchemeReferenceFixupFilter>();
 31277            })
 31278            .Replace(ServiceDescriptor.Transient<ISwaggerProvider, CachingOpenApiProvider>());
 279        }
 280
 281        private static void AddPolicy(this AuthorizationOptions authorizationOptions, string policyName, IAuthorizationR
 282        {
 480283            authorizationOptions.AddPolicy(policyName, policy =>
 480284            {
 480285                policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication).AddRequirements(authorizatio
 480286            });
 480287        }
 288
 289        /// <summary>
 290        /// Sets up the proxy configuration based on the addresses/subnets in <paramref name="allowedProxies"/>.
 291        /// </summary>
 292        /// <param name="config">The <see cref="NetworkConfiguration"/> containing the config settings.</param>
 293        /// <param name="allowedProxies">The string array to parse.</param>
 294        /// <param name="options">The <see cref="ForwardedHeadersOptions"/> instance.</param>
 295        internal static void AddProxyAddresses(NetworkConfiguration config, string[] allowedProxies, ForwardedHeadersOpt
 296        {
 38297            for (var i = 0; i < allowedProxies.Length; i++)
 298            {
 12299                if (IPAddress.TryParse(allowedProxies[i], out var addr))
 300                {
 4301                    AddIPAddress(config, options, addr, addr.AddressFamily == AddressFamily.InterNetwork ? NetworkConsta
 302                }
 8303                else if (NetworkUtils.TryParseToSubnet(allowedProxies[i], out var subnet))
 304                {
 0305                    AddIPAddress(config, options, subnet.Address, subnet.Subnet.PrefixLength);
 306                }
 8307                else if (NetworkUtils.TryParseHost(allowedProxies[i], out var addresses, config.EnableIPv4, config.Enabl
 308                {
 24309                    foreach (var address in addresses)
 310                    {
 8311                        AddIPAddress(config, options, address, address.AddressFamily == AddressFamily.InterNetwork ? Net
 312                    }
 313                }
 314            }
 7315        }
 316
 317        private static void AddIPAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, i
 318        {
 12319            if (addr.IsIPv4MappedToIPv6)
 320            {
 0321                addr = addr.MapToIPv4();
 322            }
 323
 12324            if ((!config.EnableIPv4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPv6 && addr.
 325            {
 4326                return;
 327            }
 328
 8329            if ((addr.AddressFamily == AddressFamily.InterNetwork && prefixLength == NetworkConstants.MinimumIPv4PrefixS
 330            {
 8331                options.KnownProxies.Add(addr);
 332            }
 333            else
 334            {
 0335                options.KnownIPNetworks.Add(new System.Net.IPNetwork(addr, prefixLength));
 336            }
 0337        }
 338
 339        private static void AddSwaggerTypeMappings(this SwaggerGenOptions options)
 340        {
 341            /*
 342             * TODO remove when System.Text.Json properly supports non-string keys.
 343             * Used in BaseItemDto.ImageBlurHashes
 344             */
 27345            options.MapType<Dictionary<ImageType, string>>(() =>
 27346                new OpenApiSchema
 27347                {
 27348                    Type = JsonSchemaType.Object,
 27349                    AdditionalProperties = new OpenApiSchema
 27350                    {
 27351                        Type = JsonSchemaType.String
 27352                    }
 27353                });
 354
 355            // Support dictionary with nullable string value.
 27356            options.MapType<Dictionary<string, string?>>(() =>
 27357                new OpenApiSchema
 27358                {
 27359                    Type = JsonSchemaType.Object,
 27360                    AdditionalProperties = new OpenApiSchema
 27361                    {
 27362                        Type = JsonSchemaType.String | JsonSchemaType.Null
 27363                    }
 27364                });
 365
 366            // Swashbuckle doesn't use JsonOptions to describe responses, so we need to manually describe it.
 27367            options.MapType<Version>(() => new OpenApiSchema
 27368            {
 27369                Type = JsonSchemaType.String
 27370            });
 27371        }
 372    }
 373}