aboutsummaryrefslogtreecommitdiff
path: root/Libs/VNLib.Plugins.Essentials.Oauth/src/Applications/ApplicationStore.cs
blob: 8374c2153b8f3803870b0301f6c1d26579321604 (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
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Oauth
* File: ApplicationStore.cs 
*
* ApplicationStore.cs is part of VNLib.Plugins.Essentials.Oauth which is part of the larger 
* VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Essentials.Oauth is free software: you can redistribute it and/or modify 
* it under the terms of the GNU Affero General Public License as 
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* VNLib.Plugins.Essentials.Oauth is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see https://www.gnu.org/licenses/.
*/

using System;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;

using Microsoft.EntityFrameworkCore;

using VNLib.Hashing;
using VNLib.Utils;
using VNLib.Utils.Memory;
using VNLib.Plugins.Extensions.Data;
using VNLib.Plugins.Essentials.Accounts;
using VNLib.Plugins.Essentials.Oauth.Tokens;

namespace VNLib.Plugins.Essentials.Oauth.Applications
{
    /// <summary>
    /// A DbStore for <see cref="UserApplication"/>s for OAuth2 client applications
    /// </summary>
    public sealed partial class ApplicationStore : DbStore<UserApplication>
    {
        public const int SECRET_SIZE = 32;
        public const int CLIENT_ID_SIZE = 16;

        private readonly IPasswordHashingProvider SecretHashing;
        private readonly DbContextOptions ConextOptions;
        private readonly ITokenManager TokenStore;

        /// <summary>
        /// Initializes a new <see cref="ApplicationStore"/> data store
        /// uisng the specified EFCore <see cref="DbContextOptions"/> object.
        /// </summary>
        /// <param name="conextOptions">EFCore context options for connecting to a remote data-store</param>
        /// <param name="secretHashing">A <see cref="PasswordHashing"/> structure for hashing client secrets</param>
        public ApplicationStore(DbContextOptions conextOptions, IPasswordHashingProvider secretHashing)
        {
            ConextOptions = conextOptions;
            SecretHashing = secretHashing;
            TokenStore = new TokenStore(conextOptions);
        }
      
       
        /// <summary>
        /// Updates the secret of an application, and if successful returns the new raw secret data
        /// </summary>
        /// <param name="userId">The user-id of that owns the application</param>
        /// <param name="appId">The id of the application to update</param>
        /// <returns>A task that resolves to the raw secret that was used to generate the hash, or null if the operation failed</returns>
        public async Task<PrivateString?> UpdateSecretAsync(string userId, string appId)
        {
            /*
             * Delete open apps first, incase there are any issues, worse case
             * the user's will have to re-authenticate.
             * 
             * If we delete tokens after update, the user wont see the new 
             * secret and may lose access to the updated app, not a big deal
             * but avoidable.
             */
            await TokenStore.RevokeTokensForAppAsync(appId, CancellationToken.None);
            //Generate the new secret
            PrivateString secret = GenerateSecret();
            //Hash the secret
            using PrivateString secretHash = SecretHashing.Hash(secret);
            //Open new db context
            await using UserAppContext Database = new(ConextOptions);
            //Open transaction
            await Database.OpenTransactionAsync();
            //Get the app to update the secret on 
            UserApplication? app = await (from ap in Database.OAuthApps 
                                         where ap.UserId == userId && ap.Id == appId 
                                         select ap)
                                         .SingleOrDefaultAsync();
            if (app == null)
            {
                return null;
            }
            //Store the new secret hash
            app.SecretHash = (string)secretHash;
            //Save changes
            if (await Database.SaveChangesAsync() <= 0)
            {
                return null;
            }
            //Commit transaction
            await Database.CommitTransactionAsync();
            //return the raw secret
            return secret;
        }

        /// <summary>
        /// Attempts to retreive an application by the specified client id and compares the raw secret against the 
        /// stored secret hash.
        /// </summary>
        /// <param name="clientId">The clientid of the application to search</param>
        /// <param name="secret">The secret to compare against</param>
        /// <returns>True if the application was found and the secret matches the stored secret, false if the appliation was not found or the secret does not match</returns>
        public async Task<UserApplication?> VerifyAppAsync(string clientId, PrivateString secret)
        {
            UserApplication? app;
            //Open new db context
            await using (UserAppContext Database = new(ConextOptions))
            {
                //Open transaction
                await Database.OpenTransactionAsync();
                //Get the application with its secret
                app = await (from userApp in Database.OAuthApps
                             where userApp.ClientId == clientId
                             select userApp)
                             .FirstOrDefaultAsync();
                //commit the transaction
                await Database.CommitTransactionAsync();
            }
            //make sure app exists
            if (string.IsNullOrWhiteSpace(app?.UserId) || !app.ClientId!.Equals(clientId, StringComparison.Ordinal))
            {
                //Not found or not valid
                return null;
            }
            //Convert the secret hash to a private string so it will be cleaned up
            using PrivateString secretHash = (PrivateString)app.SecretHash!;
            //Verify the secret against the hash
            if (SecretHashing.Verify(secretHash, secret))
            {
                app.SecretHash = null;
                //App was successfully verified
                return app;
            }
            //Not found or not valid
            return null;
        }
        ///<inheritdoc/>
        public override async Task<ERRNO> DeleteAsync(params string[] specifiers)
        {
            //get app id to remove tokens from
            string appId = specifiers[0];
            //Delete app from store
            ERRNO result = await base.DeleteAsync(specifiers);
            if(result)
            {
                //Delete active tokens
                await TokenStore.RevokeTokensForAppAsync(appId, CancellationToken.None);
            }
            return result;
        }      

        /// <summary>
        /// Generates a client application secret using the <see cref="RandomHash"/> library
        /// </summary>
        /// <returns>The RNG secret</returns>
        public static PrivateString GenerateSecret() => (PrivateString)RandomHash.GetRandomHex(SECRET_SIZE).ToLower()!;
        /// <summary>
        /// Creates and initializes a new <see cref="UserApplication"/> with a random clientid and 
        /// secret that must be disposed
        /// </summary>
        /// <param name="record">The new record to create</param>
        /// <returns>The result of the operation</returns>
        public override async Task<ERRNO> CreateAsync(UserApplication record)
        {
            record.RawSecret = GenerateSecret();
            //Hash the secret
            using PrivateString secretHash = SecretHashing.Hash(record.RawSecret);
            record.ClientId = GenerateClientID();
            record.SecretHash = (string)secretHash;
            //Wait for the rescord to be created before wiping the secret
            return await base.CreateAsync(record);
        }

        /// <summary>
        /// Generates a new client ID using the <see cref="RandomHash"/> library
        /// </summary>
        /// <returns>The new client ID</returns>
        public static string GenerateClientID() => RandomHash.GetRandomHex(CLIENT_ID_SIZE).ToLower();
        ///<inheritdoc/>
        public override string RecordIdBuilder => RandomHash.GetRandomHex(CLIENT_ID_SIZE).ToLower();
        ///<inheritdoc/>
        public override TransactionalDbContext NewContext() => new UserAppContext(ConextOptions);
        ///<inheritdoc/>
        protected override IQueryable<UserApplication> AddOrUpdateQueryBuilder(TransactionalDbContext context, UserApplication record)
        {
            UserAppContext ctx = (context as UserAppContext)!;
            //get a single record by the id for the specific user
            return from userApp in ctx.OAuthApps
                   where userApp.UserId == record.UserId
                   && userApp.Id == record.Id
                   select userApp;
        }
        ///<inheritdoc/>
        protected override void OnRecordUpdate(UserApplication newRecord, UserApplication currentRecord)
        {
            currentRecord.AppDescription = newRecord.AppDescription;
            currentRecord.AppName = newRecord.AppName;
        }
        ///<inheritdoc/>
        protected override IQueryable<UserApplication> GetCollectionQueryBuilder(TransactionalDbContext context, string specifier)
        {
            UserAppContext ctx = (context as UserAppContext)!;
            //Get the user's applications based on their userid
            return from userApp in ctx.OAuthApps
                   where userApp.UserId == specifier
                   orderby userApp.Created ascending
                   select new UserApplication
                   {
                       AppDescription = userApp.AppDescription,
                       Id = userApp.Id,
                       AppName = userApp.AppName,
                       ClientId = userApp.ClientId,
                       Created = userApp.Created,
                       Permissions = userApp.Permissions
                   };
        }
        ///<inheritdoc/>
        protected override IQueryable<UserApplication> GetCollectionQueryBuilder(TransactionalDbContext context, params string[] constraints)
        {
            return GetCollectionQueryBuilder(context, constraints[0]);
        }
        ///<inheritdoc/>
        protected override IQueryable<UserApplication> GetSingleQueryBuilder(TransactionalDbContext context, params string[] constraints)
        {
            string appId = constraints[0];
            string userId = constraints[1];
            UserAppContext ctx = (context as UserAppContext)!;
            //Query to get a new single application with limit results output
            return from userApp in ctx.OAuthApps
                   where userApp.UserId == userId
                   && userApp.Id == appId
                   select new UserApplication
                   {
                       AppDescription = userApp.AppDescription,
                       Id = userApp.Id,
                       AppName = userApp.AppName,
                       ClientId = userApp.ClientId,
                       Created = userApp.Created,
                       Permissions = userApp.Permissions,
                       Version = userApp.Version
                   };
        }
        ///<inheritdoc/>
        protected override IQueryable<UserApplication> GetSingleQueryBuilder(TransactionalDbContext context, UserApplication record)
        {
            //Use the query for single record with the other record's userid and record id
            return GetSingleQueryBuilder(context, record.Id, record.UserId);
        }
        ///<inheritdoc/>
        protected override IQueryable<UserApplication> UpdateQueryBuilder(TransactionalDbContext context, UserApplication record)
        {
            UserAppContext ctx = (context as UserAppContext)!;
            return from userApp in ctx.OAuthApps
                   where userApp.UserId == record.UserId && userApp.Id == record.Id
                   select userApp;
        }

        //DO NOT ALLOW PAGINATION YET
        public override Task<int> GetPageAsync(ICollection<UserApplication> collection, int page, int limit)
        {
            throw new NotSupportedException();
        }
    }
}