Files
AutopilotMonitor/src/Backend/AutopilotMonitor.Functions/Functions/Bootstrap/CreateBootstrapSessionFunction.cs
T
Oliver Kieselbach 26bcab9054 feat: move OOBE bootstrap script endpoint into the backend (go.autopilotmonitor.com)
The portal's Next.js /go/[code] route was the web app's only request-time
server code and blocked the planned static export. The script generation
now lives in the Function App as GET /api/bootstrap/go/{code}
(GetBootstrapScriptFunction), reached by customers as
irm https://go.autopilotmonitor.com/{code} | iex via a Front Door custom
domain whose /* route rewrites onto the API path.

- New Constants.BootstrapGoBaseUrl; CreateBootstrapSessionFunction now
  hands out the go URL (previously unguarded — CreateBootstrapSessionUrlShapeTests
  pins it now). go host added to both URL-guard enforced lists.
- BootstrapScriptValueValidator ports the bootstrapValidation.ts injection
  invariants (exact GUIDs, https + host allowlist + /agent/*.zip path,
  expiry <= 14d) as defense-in-depth for in-process values.
- OobeBootstrapScriptGenerator ports the PS template as a Replace-token
  raw string; golden test pins byte parity with the TS template
  (TestData/oobe-bootstrap-golden.ps1, captured from route.ts).
- Always-HTTP-200 text/plain contract incl. rate limit (own bucket
  bootstrap-script:{ip} 20/min); disabled tenant indistinguishable from
  unknown code. Catalog: PublicAnonymous; NoStoreCacheMiddleware covers
  /api/bootstrap/go/ (script inlines the bearer token).
- Web: BOOTSTRAP_GO_URL registry entry, sessions list shows the go host,
  legacy route marked LEGACY (alive for pre-migration URLs <= 168h,
  removal in the static-export PR).
- Docs: new OKF backend/oobe-bootstrap-go-flow.md, url-registry go
  section, index/log entries.

Backend tests 3611/3611, web vitest 651/651, tsc clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-28 21:42:56 +02:00

118 lines
5.1 KiB
C#

using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared;
using AutopilotMonitor.Shared.DataAccess;
using AutopilotMonitor.Shared.Models;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace AutopilotMonitor.Functions.Functions.Bootstrap
{
/// <summary>
/// POST /api/bootstrap/sessions — Create a new bootstrap session for OOBE agent deployment.
/// Requires JWT authentication and TenantAdmin role.
/// </summary>
public class CreateBootstrapSessionFunction
{
private readonly ILogger<CreateBootstrapSessionFunction> _logger;
private readonly BootstrapSessionService _bootstrapService;
private readonly TenantConfigurationService _configService;
private readonly IMaintenanceRepository _maintenanceRepo;
public CreateBootstrapSessionFunction(
ILogger<CreateBootstrapSessionFunction> logger,
BootstrapSessionService bootstrapService,
TenantConfigurationService configService,
IMaintenanceRepository maintenanceRepo)
{
_logger = logger;
_bootstrapService = bootstrapService;
_configService = configService;
_maintenanceRepo = maintenanceRepo;
}
[Function("CreateBootstrapSession")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "bootstrap/sessions")] HttpRequestData req)
{
try
{
// Authentication + BootstrapManagerOrGA authorization enforced by PolicyEnforcementMiddleware
// Cross-tenant check enforced by middleware via TenantScoping.QueryParam
var requestCtx = req.GetRequestContext();
var tenantId = requestCtx.TargetTenantId;
var userIdentifier = requestCtx.UserPrincipalName;
// Read request body
string body;
using (var reader = new StreamReader(req.Body))
body = await reader.ReadToEndAsync();
var request = JsonConvert.DeserializeObject<CreateBootstrapSessionRequest>(body);
if (request == null)
{
var badReq = req.CreateResponse(HttpStatusCode.BadRequest);
await badReq.WriteAsJsonAsync(new { error = "Invalid request body" });
return badReq;
}
// Check if bootstrap token feature is enabled for this tenant
var tenantConfig = await _configService.GetConfigurationAsync(tenantId);
if (!tenantConfig.BootstrapTokenEnabled)
{
var disabled = req.CreateResponse(HttpStatusCode.Forbidden);
await disabled.WriteAsJsonAsync(new { error = "Bootstrap token feature is not enabled for this tenant" });
return disabled;
}
// Validate validity hours
var validityHours = request.ValidityHours > 0 ? request.ValidityHours : 8;
var session = await _bootstrapService.CreateAsync(tenantId, validityHours, userIdentifier, request.Label);
await _maintenanceRepo.LogAuditEntryAsync(
tenantId,
"CREATE",
"BootstrapSession",
session.ShortCode,
userIdentifier,
new Dictionary<string, string>
{
{ "ValidityHours", validityHours.ToString() },
{ "Label", request.Label ?? string.Empty }
}
);
var responseData = new CreateBootstrapSessionResponse
{
Success = true,
ShortCode = session.ShortCode,
// go domain — Front Door rewrites /{code} to /api/bootstrap/go/{code}
// (GetBootstrapScriptFunction). URLs issued before the migration keep
// working on the legacy www /go route until the static-export cutover.
BootstrapUrl = $"{Constants.BootstrapGoBaseUrl}/{session.ShortCode}",
ExpiresAt = session.ExpiresAt,
Message = $"Bootstrap session created. Valid for {validityHours} hours."
};
var response = req.CreateResponse(HttpStatusCode.Created);
await response.WriteAsJsonAsync(responseData);
return response;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating bootstrap session");
var error = req.CreateResponse(HttpStatusCode.InternalServerError);
await error.WriteAsJsonAsync(new { error = "Failed to create bootstrap session" });
return error;
}
}
}
}