aboutsummaryrefslogtreecommitdiff
path: root/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/OAuth2SessionIdProvider.cs
blob: 597749d95b7e3275f16f129d321c9b0a7512143e (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
using System;
using System.Diagnostics.CodeAnalysis;

using VNLib.Utils.Memory;
using VNLib.Utils.Extensions;
using VNLib.Hashing;
using VNLib.Net.Http;
using VNLib.Plugins.Essentials.Extensions;
using VNLib.Plugins.Essentials.Sessions.Runtime;
using VNLib.Plugins.Essentials.Oauth.Applications;
using VNLib.Plugins.Sessions.Cache.Client;
using static VNLib.Plugins.Essentials.Oauth.OauthSessionExtensions;

namespace VNLib.Plugins.Essentials.Sessions.OAuth
{
    /// <summary>
    /// Generates secure OAuth2 session tokens and initalizes new OAuth2 sessions
    /// </summary>
    internal class OAuth2SessionIdProvider : IOauthSessionIdFactory
    {
        private readonly string SessionIdPrefix;
        private readonly int _bufferSize;
        private readonly int _tokenSize;

        ///<inheritdoc/>
        public int MaxTokensPerApp { get; }
        ///<inheritdoc/>
        public TimeSpan SessionValidFor { get; }
        ///<inheritdoc/>
        string IOauthSessionIdFactory.TokenType => "Bearer";

        public OAuth2SessionIdProvider(string sessionIdPrefix, int maxTokensPerApp, int tokenSize, TimeSpan validFor)
        {
            SessionIdPrefix = sessionIdPrefix;
            MaxTokensPerApp = maxTokensPerApp;
            SessionValidFor = validFor;
            _tokenSize = tokenSize;
            _bufferSize = tokenSize * 2;
        }
       
        ///<inheritdoc/>
        bool ISessionIdFactory.TryGetSessionId(IHttpEvent entity, [NotNullWhen(true)] out string? sessionId)
        {
            //Get authorization token and make sure its not too large to cause a buffer overflow
            if (entity.Server.HasAuthorization(out string? token) && (token.Length + SessionIdPrefix.Length) <= _bufferSize)
            {
                //Compute session id from token
                sessionId = ComputeSessionIdFromToken(token);

                return true;
            }
            else
            {
                sessionId = null;
            }

            return false;
        }

        private string ComputeSessionIdFromToken(string token)
        {
            //Buffer to copy data to
            using UnsafeMemoryHandle<char> buffer = Memory.UnsafeAlloc<char>(_bufferSize, true);

            //Writer to accumulate data
            ForwardOnlyWriter<char> writer = new(buffer.Span);

            //Append session id prefix and token
            writer.Append(SessionIdPrefix);
            writer.Append(token);

            //Compute base64 hash of token and 
            return ManagedHash.ComputeBase64Hash(writer.AsSpan(), HashAlg.SHA256);
        }

        ///<inheritdoc/>
        TokenAndSessionIdResult IOauthSessionIdFactory.GenerateTokensAndId()
        {
            //Alloc buffer for random data
            using UnsafeMemoryHandle<byte> mem = Memory.UnsafeAlloc<byte>(_tokenSize, true);
            
            //Generate token from random cng bytes
            RandomHash.GetRandomBytes(mem);
            
            //Token is the raw value
            string token = Convert.ToBase64String(mem.Span);

            //The session id is the HMAC of the token
            string sessionId = ComputeSessionIdFromToken(token);
            
            //Clear buffer
            Memory.InitializeBlock(mem.Span);
            
            //Return sessid result
            return new(sessionId, token, null);
        }

        ///<inheritdoc/>
        void IOauthSessionIdFactory.InitNewSession(RemoteSession session, UserApplication app, IHttpEvent entity)
        {
            //Store session variables
            session[APP_ID_ENTRY] = app.Id;
            session[TOKEN_TYPE_ENTRY] = "client_credential,bearer";
            session[SCOPES_ENTRY] = app.Permissions;
            session.UserID = app.UserId;
        }
    }
}