Extending
Integrations
Where the platform keeps its data is exchangeable - the database, the files and the secrets each go through an integration. Which ones exist, how a host chooses them, and how to write your own, with a complete secrets integration for OpenBao and HashiCorp Vault.
What the platform keeps goes through three integrations, one of each kind per installation. An integration keeps data - opens a connection, writes a file, stores a value - and decides nothing: whether an app may have a database, how much room it gets, who may read a secret and when a database is optimized are the platform’s rules, applied before an integration is asked. That is what makes one exchangeable for another without the rules changing with it.
The three kinds#
| Kind | Contract | Keeps | Built in |
|---|---|---|---|
| Database | IDatabaseProvider |
the platform’s records and analytics, and the database of every app and draft | SQLite files in the volume (default); PostgreSQL |
| Files | IFileProvider |
the workspace of every app and draft, and the platform’s pictures (logo, showcase) | directories in the volume |
| Secrets | ISecretProvider |
the secrets of every app and draft | sealed in the platform’s own records, wherever the database integration keeps them |
The community edition chooses the database with LAMBDA_DATABASE; everything else takes a host of your own. The panel’s Integrations section shows what an installation uses and where - never a password.
Apps do not notice: they reach their data through Database.GetConnectionAsync(), Workspace and Secret.ReadAsync, whatever keeps it.
Choosing them in a host#
C#
await using var platform = await LambdaPlatform.Create()
.Options(settings.Platform)
.Database(PostgreSqlDatabase.Create("Host=db;Database=lambda;Username=lambda;Password=…"))
.Secrets(VaultSecrets.Create("https://bao.example.com:8200", token))
.BuildAsync();
Each method takes a builder - IIntegrationBuilder<T>. An integration then lives as a GenHTTP handler does: the platform builds it once it knows where its data directory is, which only configures it; prepares each in turn - the database, the files, the secrets - before anything is migrated, which is where one reaches its server, so one that does not answer keeps the installation from starting rather than failing its first request; and disposes of them with itself, the last built first. A kind left out gets the platform’s own.
Writing your own#
An integration is a class library that references GenHTTP.Lambda.Integrations - the contracts and nothing of the platform’s - and offers a builder:
C#
public sealed class MySecretsBuilder : IIntegrationBuilder<ISecretProvider>
{
public ISecretProvider Build(IntegrationContext context) => new MySecrets(/* … */);
}
IntegrationContext hands over the data directory and the platform’s loggers. Building checks what the builder was given and reaches nothing. Every integration also implements IIntegration:
PrepareAsync(CancellationToken)- reaches the infrastructure for the first time, once, as the installation starts: check that the server answers and the credentials work, create what the integration keeps there.ValueTask.CompletedTaskwhere there is nothing to do.DisposeAsync()- lets go of what it opened: clients, pools, connections. It is called whether or not the integration was prepared - also when another one failed to prepare.Describe()- what the operator sees in the panel: a name, and where the data is, as labels and values. Never a password, token or connection string. The kind is an enum,IntegrationKind.Guide(GuideContext)- a few lines agents need to know about this integration, added to the guide’s section of its kind;nullfor none.
What every integration has to respect:
- It is awaited. Every member that reaches your infrastructure returns a
ValueTaskand takes aCancellationToken, so await your client -HttpClient.SendAsync,OpenAsync- and never wait for a task with.Resultor.Wait(): a project belowsrc/is compiled with the platform’s rules, which refuse it, and Entity Framework’s synchronous query and save methods as well. What only describes or configures -Describe,Guide- is synchronous. - It answers at once where it can. Where the infrastructure is on the same machine - a file, an embedded database - do the work and return a completed task (
ValueTask.FromResult,ValueTask.CompletedTask) rather than hop to another thread. The platform asks for a whole database or workspace - a draft’s copy, an export - away from the request’s thread, so such work may take its time there. - It keeps the engine in mind. On GenHTTP’s internal engine, which the image runs, and on Kestrel, what an integration awaits frees the thread while it waits. On the Ioxide engine (
LAMBDA_ENGINE=ioxide) a request runs on the reactor of its core, and what it awaits resumes there: an integration meant for Ioxide answers on the thread it is asked on, as SQLite and the local files do. One that waits on the network works on Ioxide too - what it awaited is handed back to the reactor once it completes, a hop between threads every time - but the internal engine or Kestrel suit it better. - Apps may still wait for it. Apps are taught the awaited forms -
await Secret.ReadAsync(…)- but code written before calls the plain ones,Secret.Read(…), which wait for an integration that does not answer at once, holding the request’s thread meanwhile. - It is addressed by scope. A
DataScopenames an app by its internal id, and a draft’s copy by the id of its feature. The platform has already checked who called; the integration never sees a key. - It throws when it cannot. An exception surfaces as an error of whatever asked - a failed save, a 500 for the editor - and an operation such as deleting an app may then stop halfway. Keep the backend available, retry where it is safe, and make deletes idempotent.
- It is asked for every app. Starting, merging and discarding a draft and deleting an app call every integration, whether the app keeps that kind of data or not - while one is unreachable, those fail for all apps.
Example: secrets in OpenBao or HashiCorp Vault#
Many organizations keep secrets in a vault, with its own access control, audit log and backups. This integration stores the apps’ secrets in the KV v2 engine of OpenBao or HashiCorp Vault - both speak the same HTTP API - one entry per app and per draft:
secret/data/genhttp-lambda/42/own the secrets of app 42
secret/data/genhttp-lambda/42/feature-7 the copy of its draft 7
The platform still decides everything else: names, sizes, how many, who may read. The values never pass through the platform’s database, so neither secrets.key nor a backup of the volume holds them.
The contract#
| Method | Asked when |
|---|---|
LoadAsync(scope) |
a running app first reads a secret; the platform keeps the answer in memory until something changes |
ListAsync(scope) |
secrets are listed or counted - names and dates, never values; also before every store |
StoreAsync(scope, name, value) |
a value is entered or replaced |
DeleteAsync(scope, name) |
one secret is removed |
CopyAsync(source, target) |
a draft starts, or its test data is reset |
DeleteAsync(scope) |
a draft is put online or discarded |
DeleteAllAsync(lambdaId) |
an app is deleted, or its secrets switched off |
Each also takes a CancellationToken, left out in this table.
The project#
src/Integrations/Acme.Lambda.Vault/Acme.Lambda.Vault.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RootNamespace>Acme.Lambda.Vault</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../GenHTTP.Lambda.Integrations/GenHTTP.Lambda.Integrations.csproj" />
</ItemGroup>
</Project>
src/Integrations/Acme.Lambda.Vault/VaultSecrets.cs
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using GenHTTP.Lambda.Integrations;
using GenHTTP.Lambda.Integrations.Secrets;
namespace Acme.Lambda.Vault;
/// <summary>
/// Keeps the secrets of the lambdas in the KV v2 engine of OpenBao or
/// HashiCorp Vault: one entry per lambda (and per draft), at
/// {mount}/data/{prefix}/{lambda}/{scope}.
/// </summary>
public static class VaultSecrets
{
public static VaultSecretsBuilder Create(string address, string token) => new(address, token);
}
public sealed class VaultSecretsBuilder(string address, string token) : IIntegrationBuilder<ISecretProvider>
{
private string _mount = "secret";
private string _prefix = "genhttp-lambda";
/// <summary>The mount of the KV v2 engine, "secret" by default.</summary>
public VaultSecretsBuilder Mount(string mount) { _mount = mount; return this; }
/// <summary>The path below the mount the entries are kept at.</summary>
public VaultSecretsBuilder Prefix(string prefix) { _prefix = prefix; return this; }
public ISecretProvider Build(IntegrationContext context) => new VaultSecretProvider(new Uri(address), token, _mount, _prefix);
}
internal sealed class VaultSecretProvider : ISecretProvider
{
private static readonly JsonSerializerOptions Options = new(JsonSerializerOptions.Web)
{
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
};
private readonly HttpClient _client;
private readonly Uri _address;
private readonly string _mount, _prefix;
public VaultSecretProvider(Uri address, string token, string mount, string prefix)
{
_address = address;
_mount = mount;
_prefix = prefix;
_client = new HttpClient { BaseAddress = address, Timeout = TimeSpan.FromSeconds(10) };
_client.DefaultRequestHeaders.Add("X-Vault-Token", token);
}
// ---- its life: the vault is asked once as the platform starts, the client let go of with it ----
/// <summary>Looks the token up: an address that does not answer, or a token the vault does not know, stops the platform from starting.</summary>
public async ValueTask PrepareAsync(CancellationToken cancellation = default)
{
using var response = await SendAsync(HttpMethod.Get, "v1/auth/token/lookup-self", cancellation);
}
public ValueTask DisposeAsync()
{
_client.Dispose();
return ValueTask.CompletedTask;
}
// ---- what the operator sees in the panel: where, never the token ----
public IntegrationInfo Describe() => new(IntegrationKind.Secrets, "OpenBao", [
new IntegrationDetail("Address", _address.ToString()),
new IntegrationDetail("Path", $"{_mount}/{_prefix}")
]);
public string? Guide(GuideContext context) => null;
// ---- reading ----
public async ValueTask<ISecretSet> LoadAsync(DataScope scope, CancellationToken cancellation = default)
=> new SecretSet((await ReadAsync(scope, cancellation)).Entries.ToDictionary(e => e.Key, e => e.Value.Value));
public async ValueTask<IReadOnlyList<SecretEntry>> ListAsync(DataScope scope, CancellationToken cancellation = default)
=> [.. (await ReadAsync(scope, cancellation)).Entries.Select(e => new SecretEntry(e.Key, e.Value.Created, e.Value.Changed))];
// ---- writing: read the entry, change it, write it back if nobody else did meanwhile ----
public async ValueTask<SecretEntry> StoreAsync(DataScope scope, string name, string value, CancellationToken cancellation = default)
{
SecretEntry? stored = null;
await ChangeAsync(scope, entries =>
{
var now = DateTime.UtcNow;
var created = entries.TryGetValue(name, out var before) ? before.Created : now;
entries[name] = new StoredSecret(value, created, now);
stored = new SecretEntry(name, created, now);
}, cancellation);
return stored!;
}
public async ValueTask<bool> DeleteAsync(DataScope scope, string name, CancellationToken cancellation = default)
{
var removed = false;
await ChangeAsync(scope, entries => removed = entries.Remove(name), cancellation);
return removed;
}
public async ValueTask CopyAsync(DataScope source, DataScope target, CancellationToken cancellation = default)
{
var entries = (await ReadAsync(source, cancellation)).Entries;
if (entries.Count == 0)
{
await DeleteAsync(target, cancellation);
}
else
{
await WriteAsync(target, entries, version: null, cancellation);
}
}
public async ValueTask DeleteAsync(DataScope scope, CancellationToken cancellation = default)
{
using var response = await SendAsync(HttpMethod.Delete, $"v1/{_mount}/metadata/{PathOf(scope)}", cancellation);
}
public async ValueTask DeleteAllAsync(long lambdaId, CancellationToken cancellation = default)
{
using var response = await SendAsync(HttpMethod.Get, $"v1/{_mount}/metadata/{_prefix}/{lambdaId}/?list=true", cancellation, allowMissing: true);
if (response.StatusCode == HttpStatusCode.NotFound) return;
foreach (var key in (await JsonAsync(response, cancellation)).GetProperty("data").GetProperty("keys").EnumerateArray())
{
using var deleted = await SendAsync(HttpMethod.Delete, $"v1/{_mount}/metadata/{_prefix}/{lambdaId}/{key.GetString()}", cancellation);
}
}
// ---- the KV v2 API, awaited: the vault is on another machine ----
private async ValueTask<Entry> ReadAsync(DataScope scope, CancellationToken cancellation)
{
using var response = await SendAsync(HttpMethod.Get, $"v1/{_mount}/data/{PathOf(scope)}", cancellation, allowMissing: true);
if (response.StatusCode == HttpStatusCode.NotFound) return new Entry([], 0);
var data = (await JsonAsync(response, cancellation)).GetProperty("data");
var entries = data.GetProperty("data").Deserialize<Dictionary<string, StoredSecret>>(Options)!;
return new Entry(entries, data.GetProperty("metadata").GetProperty("version").GetInt32());
}
private async ValueTask ChangeAsync(DataScope scope, Action<Dictionary<string, StoredSecret>> change, CancellationToken cancellation)
{
for (var attempt = 1; ; attempt++)
{
var (entries, version) = await ReadAsync(scope, cancellation);
change(entries);
// check-and-set: refused when somebody wrote the entry since it was read
if (await WriteAsync(scope, entries, version, cancellation)) return;
if (attempt == 3) throw new InvalidOperationException($"The secrets of {scope} kept changing while they were written.");
}
}
private async ValueTask<bool> WriteAsync(DataScope scope, Dictionary<string, StoredSecret> entries, int? version, CancellationToken cancellation)
{
using var request = new HttpRequestMessage(HttpMethod.Post, $"v1/{_mount}/data/{PathOf(scope)}")
{
Content = JsonContent.Create(new { data = entries, options = version is { } v ? new { cas = v } : null }, options: Options)
};
using var response = await _client.SendAsync(request, cancellation);
if (response.StatusCode == HttpStatusCode.BadRequest && version != null) return false;
response.EnsureSuccessStatusCode();
return true;
}
private async ValueTask<HttpResponseMessage> SendAsync(HttpMethod method, string path, CancellationToken cancellation, bool allowMissing = false)
{
using var request = new HttpRequestMessage(method, path);
var response = await _client.SendAsync(request, cancellation);
if (!(allowMissing && response.StatusCode == HttpStatusCode.NotFound))
{
response.EnsureSuccessStatusCode();
}
return response;
}
private static async ValueTask<JsonElement> JsonAsync(HttpResponseMessage response, CancellationToken cancellation)
{
await using var stream = await response.Content.ReadAsStreamAsync(cancellation);
using var document = await JsonDocument.ParseAsync(stream, cancellationToken: cancellation);
return document.RootElement.Clone();
}
private string PathOf(DataScope scope)
=> $"{_prefix}/{scope.LambdaId}/{(scope.FeatureId is { } feature ? $"feature-{feature}" : "own")}";
private sealed record Entry(Dictionary<string, StoredSecret> Entries, int Version);
private sealed record StoredSecret(string Value, DateTime Created, DateTime Changed);
private sealed class SecretSet(Dictionary<string, string> values) : ISecretSet
{
public int Count => values.Count;
public string? Read(string name) => values.GetValueOrDefault(name);
}
}
Wire it up#
Reference the project from your host and choose it on the platform’s builder; the custom host does it where ACME_BAO_ADDRESS is set.
KV v2 keeps earlier versions of every entry - ten by default - so a value that was replaced or deleted would stay readable in the vault. Give the platform a mount of its own that keeps one, and a token whose policy allows exactly that mount:
Shell
bao secrets enable -path=lambda-secrets kv-v2
bao write lambda-secrets/config max_versions=1 # replaced and deleted values do not linger
genhttp-lambda.hcl
path "lambda-secrets/data/genhttp-lambda/*" { capabilities = ["create", "read", "update"] }
path "lambda-secrets/metadata/genhttp-lambda/*" { capabilities = ["read", "list", "delete"] }
Shell
bao policy write genhttp-lambda genhttp-lambda.hcl
bao token create -policy=genhttp-lambda -period=768h # renew it, or use AppRole in production
As it starts, the integration looks its token up (auth/token/lookup-self), which the default policy every token gets allows; a token made with -no-default-policy needs that path in its policy as well, or the installation does not start.
C#
builder.Secrets(VaultSecrets.Create("https://bao.example.com:8200", token).Mount("lambda-secrets"));
Then enter a secret in the editor, and look: bao kv list lambda-secrets/genhttp-lambda lists the apps that keep secrets, by the platform’s internal id, and bao kv get lambda-secrets/genhttp-lambda/<id>/own shows their values - while the platform’s database holds nothing of them.
Ideas for the other kinds#
Files in object storage. The files contract is shaped for an S3-compatible store: an app reaches its files only through the platform, and nothing hands it a path. Beyond reading and writing, it asks for:
- writes that are whole or not at all, including an upload that arrives as a stream and may break off;
- folders as things of their own - an app may create an empty one and rely on it - so a store without folders keeps a marker for each;
ResourceAsyncandTree, through which files are served to visitors (GenHTTP’sIResourceandIResourceTree) - a tree is made without reaching the store, and read as it is served;- copying a whole workspace for a draft, without the old copy disappearing before the new one is complete;
- the platform’s own stores (
FileStore.Branding,FileStore.Showcase) beside the apps’ workspaces, under names of your choosing that do not change afterwards.
The asynchronous client of your storage SDK is what the contract expects. The built-in LocalFiles shows every case, answering at once since its files are on the same machine.
Another database. A database integration also carries the platform’s own schema, which exists for the dialects of DatabaseDialect only - SQLite and PostgreSQL; a provider of another one cannot be written without the platform knowing its schema. A new database is therefore a contribution to the platform rather than a project of your own - PostgreSqlDatabase shows what it takes. Its builder’s options - RolePrefix, PoolSize - are there for a host that configures PostgreSQL in code.
A database integration keeps its databases in shape as well, when it is asked to: OptimizeAsync(DatabaseStore) for one of the platform’s stores, OptimizeAsync(DataScope) for an app’s database. The platform decides which and when - once a day in the quiet hours, unless the operator switched it off - and asks from a background job, never while a request waits; the provider does what its database needs and judges what is too costly as the database is now. It answers with a DatabaseOptimization: the room before and after, the statements it ran, and what it left out and why, which the panel shows as written. A database that is not there is not made by it.