Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
ο»Ώusing System.Security.Claims;
using Bit.HttpExtensions;
using Bit.Services.Pam.Api.Models.Request;
using Bit.Services.Pam.Api.Models.Response;

namespace Bit.Services.Pam.Api.Endpoints.Handlers;

/// <summary>
/// Handler for the <c>leases</c> resource. The Minimal API endpoints (see <c>LeaseEndpoints</c>) resolve this
/// handler from DI.
/// </summary>
/// <remarks>
/// Scaffold only: the method signatures define the wire contract (request/response models, status codes) that the
/// generated OpenAPI spec and client bindings are built from. The bodies are intentionally unimplemented β€” the
/// behavior lands with the rest of the PAM feature.
/// </remarks>
public class LeaseEndpointsHandler
{
public Task<ListResponseModel<AccessLeaseResponseModel>> GetActive(ClaimsPrincipal user)
=> throw new NotImplementedException();

public Task<ListResponseModel<AccessLeaseResponseModel>> GetHistory(ClaimsPrincipal user)
=> throw new NotImplementedException();

public Task<ListResponseModel<AccessLeaseResponseModel>> GetMine(ClaimsPrincipal user)
=> throw new NotImplementedException();

public Task Revoke(ClaimsPrincipal user, Guid id, AccessLeaseRevokeRequestModel model)
=> throw new NotImplementedException();

public Task<AccessRequestDetailsResponseModel> Extend(ClaimsPrincipal user, Guid id, AccessLeaseExtensionRequestModel model)
=> throw new NotImplementedException();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
ο»Ώusing System.Security.Claims;
using Bit.Services.Pam.Api.Endpoints.Handlers;
using Bit.Services.Pam.Api.Models.Request;

namespace Bit.Services.Pam.Api.Endpoints;

/// <summary>
/// The <c>leases</c> resource: the caller's own leases, the governance surface over manageable collections, and the
/// per-lease actions (revoke, extend).
/// </summary>
internal static class LeaseEndpoints
{
public static RouteGroupBuilder MapLeaseEndpoints(this RouteGroupBuilder group)
{
group.WithTags("Leases");

group.MapGet("active", (LeaseEndpointsHandler handler, ClaimsPrincipal user) => handler.GetActive(user))
.WithName("Pam_Leases_GetActive");

group.MapGet("history", (LeaseEndpointsHandler handler, ClaimsPrincipal user) => handler.GetHistory(user))
.WithName("Pam_Leases_GetHistory");

group.MapGet("mine", (LeaseEndpointsHandler handler, ClaimsPrincipal user) => handler.GetMine(user))
.WithName("Pam_Leases_GetMine");

group.MapPost("{id:guid}/revoke",
async (Guid id, AccessLeaseRevokeRequestModel model, LeaseEndpointsHandler handler, ClaimsPrincipal user) =>
{
await handler.Revoke(user, id, model);
return TypedResults.NoContent();
})
.WithName("Pam_Leases_Revoke");

group.MapPost("{id:guid}/extend",
(Guid id, AccessLeaseExtensionRequestModel model, LeaseEndpointsHandler handler, ClaimsPrincipal user) =>
handler.Extend(user, id, model))
.WithName("Pam_Leases_Extend");

return group;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public static class PamEndpointsExtensions
{
public static void MapPamEndpoints(this IEndpointRouteBuilder endpoints)
{
endpoints.MapGroup("/leases").WithPamDefaults().MapLeaseEndpoints();
endpoints.MapGroup("/access-requests").WithPamDefaults().MapAccessRequestEndpoints();
endpoints.MapGroup("/organizations/{orgId:guid}/access-rules").WithPamDefaults().MapAccessRuleEndpoints();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
ο»Ώusing System.ComponentModel.DataAnnotations;

namespace Bit.Services.Pam.Api.Models.Request;

/// <summary>
/// A request to extend an active lease, identified by the route's lease id. The lease's end is pushed out by
/// <see cref="DurationSeconds"/>; a justifying <see cref="Reason"/> is required. Extensions are always auto-approved,
/// subject to the governing rule allowing extensions and the per-lease maximum not being reached.
/// </summary>
public class AccessLeaseExtensionRequestModel
{
/// <summary>
/// How far the lease's end is pushed out, in seconds. Must be positive and no longer than the governing rule's
/// maximum extension duration.
/// </summary>
[Range(1, int.MaxValue)]
public int DurationSeconds { get; set; }

/// <summary>
/// The justification recorded with the extension. Required to be non-empty.
/// </summary>
[Required]
public string? Reason { get; set; }
}
Comment thread
Hinton marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
ο»Ώnamespace Bit.Services.Pam.Api.Models.Request;

/// <summary>
/// A request to revoke an active lease early. <see cref="Reason"/> is optional and retained for the audit trail.
/// </summary>
public class AccessLeaseRevokeRequestModel
{
/// <summary>
/// An optional note explaining the revocation. Recorded on the audit trail; not surfaced on the lease itself.
/// </summary>
public string? Reason { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public static class ServiceCollectionExtensions
public static IServiceCollection AddPamServices(this IServiceCollection services)
{
// Minimal API endpoint handlers. The endpoints (see PamEndpointsExtensions) resolve these from DI.
services.AddScoped<LeaseEndpointsHandler>();
services.AddScoped<AccessRequestEndpointsHandler>();
services.AddScoped<AccessRuleEndpointsHandler>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ private static List<RouteEndpoint> MaterializeEndpoints()
// The handlers must be known services so Minimal API binding treats the handler parameter as injected
// (not an inferred request body) β€” the same registration AddPamServices performs in the app.
// MapPamEndpoints maps every PAM group, so each group's handler has to be resolvable here.
builder.Services.AddScoped<LeaseEndpointsHandler>();
builder.Services.AddScoped<AccessRequestEndpointsHandler>();
builder.Services.AddScoped<AccessRuleEndpointsHandler>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ private static List<RouteEndpoint> MaterializeEndpoints()
// The handlers must be known services so Minimal API binding treats the handler parameter as injected
// (not an inferred request body) β€” the same registration AddPamServices performs in the app.
// MapPamEndpoints maps every PAM group, so each group's handler has to be resolvable here.
builder.Services.AddScoped<LeaseEndpointsHandler>();
builder.Services.AddScoped<AccessRequestEndpointsHandler>();
builder.Services.AddScoped<AccessRuleEndpointsHandler>();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
ο»Ώusing Bit.Core.Models.Api;
using Bit.HttpExtensions;
using Bit.Services.Pam.Api.Endpoints;
using Bit.Services.Pam.Api.Endpoints.Handlers;
using Bit.Services.Pam.Api.Models.Response;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

namespace Bit.Services.Pam.Test.Api.Endpoints;

/// <summary>
/// Locks the lease wire contract that the generated OpenAPI spec β€” and the client bindings built from it β€”
/// depend on. The endpoint bodies are scaffold stubs; the contract (routes, names, methods, return types) is the
/// thing under test. Endpoints are materialized by mapping them onto a minimal host and reading its
/// <see cref="EndpointDataSource"/> β€” the same metadata the offline OpenAPI generator inspects.
/// </summary>
public class LeaseEndpointsTests
{
private static List<RouteEndpoint> MaterializeEndpoints()
{
var builder = WebApplication.CreateSlimBuilder();
// The handlers must be known services so Minimal API binding treats the handler parameter as injected
// (not an inferred request body) β€” the same registration AddPamServices performs in the app.
// MapPamEndpoints maps every PAM group, so each group's handler has to be resolvable here.
builder.Services.AddScoped<LeaseEndpointsHandler>();
builder.Services.AddScoped<AccessRequestEndpointsHandler>();
builder.Services.AddScoped<AccessRuleEndpointsHandler>();

var app = builder.Build();
app.MapPamEndpoints();

// Enumerating the data sources builds the endpoints β€” applying the route group's prefix, metadata, and
// conventions β€” without starting the request pipeline, the same set the OpenAPI generator discovers.
return ((IEndpointRouteBuilder)app).DataSources
.SelectMany(dataSource => dataSource.Endpoints)
.OfType<RouteEndpoint>()
.ToList();
}

[Fact]
public void MapPamEndpoints_RegistersTheFiveLeaseRoutes_InTheInternalDoc()
{
var endpoints = MaterializeEndpoints()
.Where(e => e.Metadata.GetMetadata<ITagsMetadata>()!.Tags.Contains("Leases"))
.ToList();

Assert.Equal(5, endpoints.Count);
Assert.All(endpoints, endpoint =>
Assert.Equal("internal", endpoint.Metadata.GetMetadata<IEndpointGroupNameMetadata>()?.EndpointGroupName));
}

[Theory]
[InlineData("Pam_Leases_GetActive", "GET", "leases/active")]
[InlineData("Pam_Leases_GetHistory", "GET", "leases/history")]
[InlineData("Pam_Leases_GetMine", "GET", "leases/mine")]
[InlineData("Pam_Leases_Revoke", "POST", "leases/{id:guid}/revoke")]
[InlineData("Pam_Leases_Extend", "POST", "leases/{id:guid}/extend")]
public void MapPamEndpoints_RegistersExpectedRoute(string name, string method, string route)
{
var endpoints = MaterializeEndpoints();

var endpoint = Assert.Single(
endpoints,
e => e.Metadata.GetMetadata<IEndpointNameMetadata>()?.EndpointName == name);
// Trim slashes: the raw pattern carries routing's leading/trailing slashes (e.g. "/leases/active")
// that the generated spec path does not.
Assert.Equal(route, endpoint.RoutePattern.RawText?.Trim('/'));
Assert.Contains(method, endpoint.Metadata.GetMetadata<HttpMethodMetadata>()!.HttpMethods);
}

[Fact]
public void LeaseGroup_DocumentsErrorResponseModel_For400And404()
{
var endpoint = MaterializeEndpoints()
.First(e => e.Metadata.GetMetadata<ITagsMetadata>()!.Tags.Contains("Leases"));
var produces = endpoint.Metadata.GetOrderedMetadata<IProducesResponseTypeMetadata>();

Assert.Contains(produces, p => p.StatusCode == StatusCodes.Status400BadRequest && p.Type == typeof(ErrorResponseModel));
Assert.Contains(produces, p => p.StatusCode == StatusCodes.Status404NotFound && p.Type == typeof(ErrorResponseModel));
}

[Theory]
[InlineData(nameof(LeaseEndpointsHandler.GetActive), typeof(Task<ListResponseModel<AccessLeaseResponseModel>>))]
[InlineData(nameof(LeaseEndpointsHandler.GetHistory), typeof(Task<ListResponseModel<AccessLeaseResponseModel>>))]
[InlineData(nameof(LeaseEndpointsHandler.GetMine), typeof(Task<ListResponseModel<AccessLeaseResponseModel>>))]
[InlineData(nameof(LeaseEndpointsHandler.Revoke), typeof(Task))]
[InlineData(nameof(LeaseEndpointsHandler.Extend), typeof(Task<AccessRequestDetailsResponseModel>))]
public void Handler_HasExpectedReturnType(string methodName, Type expectedReturnType)
{
var method = typeof(LeaseEndpointsHandler).GetMethod(methodName);

Assert.NotNull(method);
Assert.Equal(expectedReturnType, method!.ReturnType);
}
}
Loading