aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Server.Implementations/Security/AuthorizationContext.cs
blob: d648f9504c4043b7eb6f6396ecde8fb0857bf0ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#pragma warning disable CS1591

using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Net.Http.Headers;

namespace Jellyfin.Server.Implementations.Security
{
    public class AuthorizationContext : IAuthorizationContext
    {
        private readonly JellyfinDbProvider _jellyfinDbProvider;
        private readonly IUserManager _userManager;

        public AuthorizationContext(JellyfinDbProvider jellyfinDb, IUserManager userManager)
        {
            _jellyfinDbProvider = jellyfinDb;
            _userManager = userManager;
        }

        public Task<AuthorizationInfo> GetAuthorizationInfo(HttpContext requestContext)
        {
            if (requestContext.Request.HttpContext.Items.TryGetValue("AuthorizationInfo", out var cached) && cached != null)
            {
                return Task.FromResult((AuthorizationInfo)cached); // Cache should never contain null
            }

            return GetAuthorization(requestContext);
        }

        public async Task<AuthorizationInfo> GetAuthorizationInfo(HttpRequest requestContext)
        {
            var auth = GetAuthorizationDictionary(requestContext);
            var authInfo = await GetAuthorizationInfoFromDictionary(auth, requestContext.Headers, requestContext.Query).ConfigureAwait(false);
            return authInfo;
        }

        /// <summary>
        /// Gets the authorization.
        /// </summary>
        /// <param name="httpReq">The HTTP req.</param>
        /// <returns>Dictionary{System.StringSystem.String}.</returns>
        private async Task<AuthorizationInfo> GetAuthorization(HttpContext httpReq)
        {
            var auth = GetAuthorizationDictionary(httpReq);
            var authInfo = await GetAuthorizationInfoFromDictionary(auth, httpReq.Request.Headers, httpReq.Request.Query).ConfigureAwait(false);

            httpReq.Request.HttpContext.Items["AuthorizationInfo"] = authInfo;
            return authInfo;
        }

        private async Task<AuthorizationInfo> GetAuthorizationInfoFromDictionary(
            IReadOnlyDictionary<string, string>? auth,
            IHeaderDictionary headers,
            IQueryCollection queryString)
        {
            string? deviceId = null;
            string? deviceName = null;
            string? client = null;
            string? version = null;
            string? token = null;

            if (auth != null)
            {
                auth.TryGetValue("DeviceId", out deviceId);
                auth.TryGetValue("Device", out deviceName);
                auth.TryGetValue("Client", out client);
                auth.TryGetValue("Version", out version);
                auth.TryGetValue("Token", out token);
            }

#pragma warning disable CA1508 // string.IsNullOrEmpty(token) is always false.
            if (string.IsNullOrEmpty(token))
            {
                token = headers["X-Emby-Token"];
            }

            if (string.IsNullOrEmpty(token))
            {
                token = headers["X-MediaBrowser-Token"];
            }

            if (string.IsNullOrEmpty(token))
            {
                token = queryString["ApiKey"];
            }

            // TODO deprecate this query parameter.
            if (string.IsNullOrEmpty(token))
            {
                token = queryString["api_key"];
            }

            var authInfo = new AuthorizationInfo
            {
                Client = client,
                Device = deviceName,
                DeviceId = deviceId,
                Version = version,
                Token = token,
                IsAuthenticated = false,
                HasToken = false
            };

            if (string.IsNullOrWhiteSpace(token))
            {
                // Request doesn't contain a token.
                return authInfo;
            }
#pragma warning restore CA1508

            authInfo.HasToken = true;
            await using var dbContext = _jellyfinDbProvider.CreateContext();
            var device = await dbContext.Devices.FirstOrDefaultAsync(d => d.AccessToken == token).ConfigureAwait(false);

            if (device != null)
            {
                authInfo.IsAuthenticated = true;
                var updateToken = false;

                // TODO: Remove these checks for IsNullOrWhiteSpace
                if (string.IsNullOrWhiteSpace(authInfo.Client))
                {
                    authInfo.Client = device.AppName;
                }

                if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
                {
                    authInfo.DeviceId = device.DeviceId;
                }

                // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
                var allowTokenInfoUpdate = !authInfo.Client.Contains("chromecast", StringComparison.OrdinalIgnoreCase);

                if (string.IsNullOrWhiteSpace(authInfo.Device))
                {
                    authInfo.Device = device.DeviceName;
                }
                else if (!string.Equals(authInfo.Device, device.DeviceName, StringComparison.OrdinalIgnoreCase))
                {
                    if (allowTokenInfoUpdate)
                    {
                        updateToken = true;
                        device.DeviceName = authInfo.Device;
                    }
                }

                if (string.IsNullOrWhiteSpace(authInfo.Version))
                {
                    authInfo.Version = device.AppVersion;
                }
                else if (!string.Equals(authInfo.Version, device.AppVersion, StringComparison.OrdinalIgnoreCase))
                {
                    if (allowTokenInfoUpdate)
                    {
                        updateToken = true;
                        device.AppVersion = authInfo.Version;
                    }
                }

                if ((DateTime.UtcNow - device.DateLastActivity).TotalMinutes > 3)
                {
                    device.DateLastActivity = DateTime.UtcNow;
                    updateToken = true;
                }

                authInfo.User = _userManager.GetUserById(device.UserId);

                if (updateToken)
                {
                    dbContext.Devices.Update(device);
                    await dbContext.SaveChangesAsync().ConfigureAwait(false);
                }
            }
            else
            {
                var key = await dbContext.ApiKeys.FirstOrDefaultAsync(apiKey => apiKey.AccessToken == token).ConfigureAwait(false);
                if (key != null)
                {
                    authInfo.IsAuthenticated = true;
                    authInfo.Client = key.Name;
                    authInfo.Token = key.AccessToken;
                    if(string.IsNullOrWhiteSpace(authInfo.DeviceId))
                    {
                        authInfo.DeviceId = string.Empty;
                    }

                    if(string.IsNullOrWhiteSpace(authInfo.Device))
                    {
                        authInfo.Device = string.Empty;
                    }

                    if(string.IsNullOrWhiteSpace(authInfo.Version))
                    {
                        authInfo.Version = string.Empty;
                    }

                    authInfo.IsApiKey = true;
                }
            }

            return authInfo;
        }

        /// <summary>
        /// Gets the auth.
        /// </summary>
        /// <param name="httpReq">The HTTP req.</param>
        /// <returns>Dictionary{System.StringSystem.String}.</returns>
        private static Dictionary<string, string>? GetAuthorizationDictionary(HttpContext httpReq)
        {
            var auth = httpReq.Request.Headers["X-Emby-Authorization"];

            if (string.IsNullOrEmpty(auth))
            {
                auth = httpReq.Request.Headers[HeaderNames.Authorization];
            }

            return auth.Count > 0 ? GetAuthorization(auth[0]) : null;
        }

        /// <summary>
        /// Gets the auth.
        /// </summary>
        /// <param name="httpReq">The HTTP req.</param>
        /// <returns>Dictionary{System.StringSystem.String}.</returns>
        private static Dictionary<string, string>? GetAuthorizationDictionary(HttpRequest httpReq)
        {
            var auth = httpReq.Headers["X-Emby-Authorization"];

            if (string.IsNullOrEmpty(auth))
            {
                auth = httpReq.Headers[HeaderNames.Authorization];
            }

            return auth.Count > 0 ? GetAuthorization(auth[0]) : null;
        }

        /// <summary>
        /// Gets the authorization.
        /// </summary>
        /// <param name="authorizationHeader">The authorization header.</param>
        /// <returns>Dictionary{System.StringSystem.String}.</returns>
        private static Dictionary<string, string>? GetAuthorization(ReadOnlySpan<char> authorizationHeader)
        {
            var firstSpace = authorizationHeader.IndexOf(' ');

            // There should be at least two parts
            if (firstSpace == -1)
            {
                return null;
            }

            var name = authorizationHeader[..firstSpace];

            if (!name.Equals("MediaBrowser", StringComparison.OrdinalIgnoreCase)
                && !name.Equals("Emby", StringComparison.OrdinalIgnoreCase))
            {
                return null;
            }

            // Remove up until the first space
            authorizationHeader = authorizationHeader[(firstSpace + 1)..];
            return GetParts(authorizationHeader);
        }

        /// <summary>
        /// Get the authorization header components.
        /// </summary>
        /// <param name="authorizationHeader">The authorization header.</param>
        /// <returns>Dictionary{System.StringSystem.String}.</returns>
        public static Dictionary<string, string> GetParts(ReadOnlySpan<char> authorizationHeader)
        {
            var result = new Dictionary<string, string>();
            var escaped = false;
            int start = 0;
            string key = string.Empty;

            int i;
            for (i = 0; i < authorizationHeader.Length; i++)
            {
                var token = authorizationHeader[i];
                if (token == '"' || token == ',')
                {
                    // Applying a XOR logic to evaluate whether it is opening or closing a value
                    escaped = (!escaped) == (token == '"');
                    if (token == ',' && !escaped)
                    {
                        // Meeting a comma after a closing escape char means the value is complete
                        if (start < i)
                        {
                            result[key] = WebUtility.UrlDecode(authorizationHeader[start..i].Trim('"').ToString());
                            key = string.Empty;
                        }

                        start = i + 1;
                    }
                }
                else if (!escaped && token == '=')
                {
                    key = authorizationHeader[start.. i].Trim().ToString();
                    start = i + 1;
                }
            }

            // Add last value
            if (start < i)
            {
                result[key] = WebUtility.UrlDecode(authorizationHeader[start..i].Trim('"').ToString());
            }

            return result;
        }
    }
}