Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SM-324] Add Organization to JWT claim #2379

Merged
merged 6 commits into from
Nov 14, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/Core/Entities/ApiKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ public class ApiKey : ITableObject<Guid>
public string EncryptedPayload { get; set; }
// Key for decrypting `EncryptedPayload`. Encrypted using the organization key.
public string Key { get; set; }
public DateTime ExpireAt { get; internal set; }
public DateTime CreationDate { get; internal set; } = DateTime.UtcNow;
public DateTime RevisionDate { get; internal set; } = DateTime.UtcNow;
public DateTime ExpireAt { get; set; }
public DateTime CreationDate { get; set; } = DateTime.UtcNow;
public DateTime RevisionDate { get; set; } = DateTime.UtcNow;
Hinton marked this conversation as resolved.
Show resolved Hide resolved

public void SetNewId()
{
Expand Down
3 changes: 3 additions & 0 deletions src/Core/Identity/Claims.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,7 @@ public static class Claims
public const string OrganizationCustom = "orgcustom";
public const string ProviderAdmin = "providerprovideradmin";
public const string ProviderServiceUser = "providerserviceuser";

// Service Account
public const string Organization = "organization";
}
10 changes: 10 additions & 0 deletions src/Core/Models/Data/ApiKeyDetails.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using Bit.Core.Entities;

namespace Bit.Core.Models.Data;

public class ApiKeyDetails : ApiKey
{
public ApiKeyDetails() { }

public Guid ServiceAccountOrganizationId { get; set; }
MGibson1 marked this conversation as resolved.
Show resolved Hide resolved
}
2 changes: 2 additions & 0 deletions src/Core/Repositories/IApiKeyRepository.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using Bit.Core.Entities;
using Bit.Core.Models.Data;

namespace Bit.Core.Repositories;

public interface IApiKeyRepository : IRepository<ApiKey, Guid>
{
Task<ApiKeyDetails> GetDetailsByIdAsync(Guid id);
}
2 changes: 1 addition & 1 deletion src/Identity/IdentityServer/ApiResources.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public static IEnumerable<ApiResource> GetApiResources()
new(ApiScopes.ApiLicensing, new[] { JwtClaimTypes.Subject }),
new(ApiScopes.ApiOrganization, new[] { JwtClaimTypes.Subject }),
new(ApiScopes.ApiInstallation, new[] { JwtClaimTypes.Subject }),
new(ApiScopes.ApiSecrets, new[] { JwtClaimTypes.Subject }),
new(ApiScopes.ApiSecrets, new[] { JwtClaimTypes.Subject, Claims.Organization }),
};
}
}
4 changes: 3 additions & 1 deletion src/Identity/IdentityServer/ClientStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Security.Claims;
using Bit.Core.Context;
using Bit.Core.Enums;
using Bit.Core.Identity;
using Bit.Core.IdentityServer;
using Bit.Core.Repositories;
using Bit.Core.Services;
Expand Down Expand Up @@ -86,7 +87,7 @@ public async Task<Client> FindClientByIdAsync(string clientId)

private async Task<Client> CreateApiKeyClientAsync(string clientId)
{
var apiKey = await _apiKeyRepository.GetByIdAsync(new Guid(clientId));
var apiKey = await _apiKeyRepository.GetDetailsByIdAsync(new Guid(clientId));

if (apiKey == null || apiKey.ExpireAt <= DateTime.Now)
{
Expand All @@ -108,6 +109,7 @@ private async Task<Client> CreateApiKeyClientAsync(string clientId)
Claims = new List<ClientClaim>
{
new(JwtClaimTypes.Subject, apiKey.ServiceAccountId.ToString()),
new(Claims.Organization, apiKey.ServiceAccountOrganizationId.ToString())
Hinton marked this conversation as resolved.
Show resolved Hide resolved
},
};
}
Expand Down
17 changes: 16 additions & 1 deletion src/Infrastructure.Dapper/Repositories/ApiKeyRepository.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
using Bit.Core.Entities;
using System.Data;
using Bit.Core.Entities;
using Bit.Core.Models.Data;
using Bit.Core.Repositories;
using Bit.Core.Settings;
using Dapper;
using Microsoft.Data.SqlClient;

namespace Bit.Infrastructure.Dapper.Repositories;

Expand All @@ -13,4 +17,15 @@ public ApiKeyRepository(GlobalSettings globalSettings)
public ApiKeyRepository(string connectionString, string readOnlyConnectionString)
: base(connectionString, readOnlyConnectionString)
{ }

public async Task<ApiKeyDetails> GetDetailsByIdAsync(Guid id)
{
using var connection = new SqlConnection(ConnectionString);
var results = await connection.QueryAsync<ApiKeyDetails>(
$"[{Schema}].[ApiKeyDetails_ReadById]",
new { Id = id },
commandType: CommandType.StoredProcedure);

return results.SingleOrDefault();
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using AutoMapper;
using Bit.Core.Models.Data;
using Bit.Core.Repositories;
using Bit.Infrastructure.EntityFramework.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace Bit.Infrastructure.EntityFramework.Repositories;
Expand All @@ -11,4 +13,30 @@ public ApiKeyRepository(IServiceScopeFactory serviceScopeFactory, IMapper mapper
: base(serviceScopeFactory, mapper, (DatabaseContext context) => context.ApiKeys)
{
}

public async Task<ApiKeyDetails> GetDetailsByIdAsync(Guid id)
{
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
var entity = await GetDbSet(dbContext)
.Where(apiKey => apiKey.Id == id)
.Include(apiKey => apiKey.ServiceAccount)
.Select(apiKey => new ApiKeyDetails
{
Id = apiKey.Id,
ServiceAccountId = apiKey.ServiceAccountId,
Name = apiKey.Name,
ClientSecret = apiKey.ClientSecret,
Scope = apiKey.Scope,
EncryptedPayload = apiKey.EncryptedPayload,
Key = apiKey.Key,
ExpireAt = apiKey.ExpireAt,
CreationDate = apiKey.CreationDate,
RevisionDate = apiKey.RevisionDate,
ServiceAccountOrganizationId = apiKey.ServiceAccount.OrganizationId
})
.FirstOrDefaultAsync();

return Mapper.Map<ApiKeyDetails>(entity);
}
}
4 changes: 3 additions & 1 deletion src/Sql/Sql.sqlproj
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@
<Build Include="dbo\Functions\PolicyApplicableToUser.sql" />
<Build Include="dbo\Functions\UserCipherDetails.sql" />
<Build Include="dbo\Functions\UserCollectionDetails.sql" />
<Build Include="dbo\Stored Procedures\ApiKey_ReadById.sql" />
<Build Include="dbo\Stored Procedures\ApiKey\ApiKey_ReadById.sql" />
<Build Include="dbo\Stored Procedures\ApiKey\ApiKeyDetails_ReadById.sql" />
<Build Include="dbo\Stored Procedures\AuthRequest_Create.sql" />
<Build Include="dbo\Stored Procedures\AuthRequest_DeleteById.sql" />
<Build Include="dbo\Stored Procedures\AuthRequest_DeleteIfExpired.sql" />
Expand Down Expand Up @@ -391,6 +392,7 @@
<Build Include="dbo\User Defined Types\OrganizationUserType.sql" />
<Build Include="dbo\User Defined Types\SelectionReadOnlyArray.sql" />
<Build Include="dbo\User Defined Types\TwoGuidIdArray.sql" />
<Build Include="dbo\Views\ApiKeyDetailsView.sql" />
<Build Include="dbo\Views\ApiKeyView.sql" />
<Build Include="dbo\Views\AuthRequestView.sql" />
<Build Include="dbo\Views\CipherView.sql" />
Expand Down
13 changes: 13 additions & 0 deletions src/Sql/dbo/Stored Procedures/ApiKey/ApiKeyDetails_ReadById.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
CREATE PROCEDURE [dbo].[ApiKeyDetails_ReadById]
@Id UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON

SELECT
*
FROM
[dbo].[ApiKeyDetailsView]
WHERE
[Id] = @Id
END
9 changes: 9 additions & 0 deletions src/Sql/dbo/Views/ApiKeyDetailsView.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
CREATE VIEW [dbo].[ApiKeyDetailsView]
MGibson1 marked this conversation as resolved.
Show resolved Hide resolved
AS
SELECT
AK.*,
SA.[OrganizationId] ServiceAccountOrganizationId
FROM
[dbo].[ApiKey] AS AK
LEFT JOIN
[dbo].[ServiceAccount] SA ON SA.[Id] = AK.[ServiceAccountId]
3 changes: 2 additions & 1 deletion test/Identity.IntegrationTest/openid-configuration.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
"orgcustom",
"providerprovideradmin",
"providerserviceuser",
"sub"
"sub",
"organization"
],
"grant_types_supported": [
"authorization_code",
Expand Down
24 changes: 24 additions & 0 deletions util/Migrator/DbScripts/2022-11-03_00_ApiKeyDetails.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
CREATE OR ALTER VIEW [dbo].[ApiKeyDetailsView]
AS
SELECT
AK.*,
SA.[OrganizationId] ServiceAccountOrganizationId
FROM
[dbo].[ApiKey] AS AK
LEFT JOIN
[dbo].[ServiceAccount] SA ON SA.[Id] = AK.[ServiceAccountId]
GO

CREATE OR ALTER PROCEDURE [dbo].[ApiKeyDetails_ReadById]
@Id UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON

SELECT
*
FROM
[dbo].[ApiKeyDetailsView]
WHERE
[Id] = @Id
END