Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
4940559
feat(selfhost): add encrypted backups and guarded operations
raphaeltm Nov 19, 2026
4c41531
fix(selfhost): prove rollback and teardown ownership at deletion
raphaeltm Nov 19, 2026
faf03e4
refactor(selfhost): address operations analysis findings
raphaeltm Nov 19, 2026
f546d91
fix(selfhost): require the selected backup writer to be running
raphaeltm Nov 19, 2026
761662d
fix(selfhost): make recovery retryable and receipt identity grants
raphaeltm Nov 19, 2026
cd2e646
fix(selfhost): retain rollback progress until recovered service is he…
raphaeltm Nov 19, 2026
c478397
fix(selfhost): clean readonly Go caches during rollback
raphaeltm Nov 19, 2026
8f7882d
fix(selfhost): preserve restore ownership and recover interrupted ope…
raphaeltm Nov 19, 2026
39f3fa9
fix(selfhost): isolate restore identity and bind destructive retries
raphaeltm Nov 20, 2026
1b8c925
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 20, 2026
a29aadf
docs(selfhost): archive verified L24 operations evidence
raphaeltm Nov 20, 2026
99960ba
fix(selfhost): make interrupted operations safely retryable
raphaeltm Nov 20, 2026
73d673f
Merge main and validate combined self-host operations
raphaeltm Nov 20, 2026
a2a45b8
fix(selfhost): print the restored target health URL
raphaeltm Nov 20, 2026
2895321
fix(selfhost): persist IAM grant ownership before cloud mutation
raphaeltm Nov 20, 2026
5bbbe61
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 20, 2026
53ca778
test(selfhost): handle restore overloads in scanner controls
raphaeltm Nov 20, 2026
45f783b
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 20, 2026
afd19c8
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 20, 2026
0755f69
fix(selfhost): resume interrupted rollback state swaps
raphaeltm Nov 20, 2026
b23b995
Merge remote-tracking branch 'origin/main' into sam/self-host-landing…
raphaeltm Nov 20, 2026
d436de5
fix(selfhost): reserve independent clone identities and protect proje…
raphaeltm Nov 20, 2026
be24db7
fix(selfhost): commit healthy upgrade and recovery before cleanup
raphaeltm Nov 20, 2026
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
13 changes: 11 additions & 2 deletions deploy/selfhost/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ GCP_PROJECT=
# Optional services: `tunnel` runs frps for nodes; `local-store` runs the bundled object store
# (trials only); `mail-collector` and `mail-in` are described below.
COMPOSE_PROFILES=tunnel,gce
# Required before running Compose: run `pnpm selfhost:deploy --init`, then copy the
# installation-specific project name it prints here. Never share it with another installation.
# COMPOSE_PROJECT_NAME=sam-selfhost-<printed suffix>

# Fleet bucket. Google Cloud Storage via Application Default Credentials (on GCE, the VM's
# service account needs roles/storage.objectAdmin on the bucket):
Expand All @@ -32,6 +35,7 @@ CELLD_BUCKET=gs://my-sam-bucket/celld
# CELLD_BUCKET=s3://celld-fleet
# S3_ENDPOINT=http://127.0.0.1:9000
# AWS_ACCESS_KEY_ID=sam-objectstore
# R2_S3_REGION=us-east-1 # REQUIRED for every s3:// operator store
# AWS_SECRET_ACCESS_KEY= # at least 24 characters (the store refuses less): openssl rand -hex 24

# Loopback ports (host network). Change only on conflict, and only here: a variable set in the
Expand All @@ -52,8 +56,7 @@ CELLD_BUCKET=gs://my-sam-bucket/celld
# as R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY in .state/secrets.env (never the fleet credential).
# The deploy derives the bucket and key prefix. Unset: presigned uploads stay off.
# R2_S3_REGION is the store's SigV4 signing region: "auto" by default for a gs:// bucket,
# REQUIRED for an s3:// bucket (MinIO usually us-east-1): the deploy refuses R2_S3_ENDPOINT
# without it.
# REQUIRED for every s3:// operator store (MinIO usually us-east-1), including backup/restore.
# R2_S3_ENDPOINT=https://storage.googleapis.com
# R2_S3_REGION=auto

Expand Down Expand Up @@ -98,6 +101,12 @@ CELLD_BUCKET=gs://my-sam-bucket/celld
# Where `pnpm selfhost:deploy` keeps platform keys, gateway.env and the celld project.
# SAM_SELFHOST_STATE_DIR=./.state

# Encrypted backups and automatic upgrade recovery require a separate operator-owned raw
# 32-byte key, mode 0600. Keep it outside state and backup directories, with an offline copy.
# Generate it directly into a private file; never print it (README, Backup and restore).
# Use an absolute path: this file does not expand $HOME.
# SAM_BACKUP_KEY_FILE=/absolute/private/path/to/backup.key

# frp connections Caddy accepts per client address per window at wss://api.SAM_DOMAIN/~!frp
# (each one is a Login the Worker checks). Nodes keep one connection each; raise it if many nodes
# share one public address (a NAT gateway). Window: 1s-99s, 1m-99m or 1h.
Expand Down
1 change: 1 addition & 0 deletions deploy/selfhost/.gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Operator configuration and box state (platform keys, secrets.env, gateway.env): never commit.
.env
.state/
*.restore-progress.json
backups/
293 changes: 269 additions & 24 deletions deploy/selfhost/README.md

Large diffs are not rendered by default.

37 changes: 37 additions & 0 deletions deploy/selfhost/created-resources.d.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Types for created-resources.mjs (the record of what an install created; no secrets).
export const FORMAT: 'sam-created-resources/1';

export interface CreatedResource {
cloud: string;
kind: string;
name: string;
attributes?: Record<string, string>;
createdBy: string;
action: 'created' | 'reused';
createdAt?: string;
removedAt?: string;
}

export interface CreatedResourcesRecord {
format: typeof FORMAT;
resources: CreatedResource[];
}

export function readRecord(file: string): CreatedResourcesRecord;
export function addResource(
file: string,
entry: Omit<CreatedResource, 'createdAt' | 'removedAt'>,
now?: Date
): void;
export function markRemoved(
file: string,
cloud: string,
kind: string,
name: string,
now?: Date
): void;

export function grantIntent(
file: string,
entry: Omit<CreatedResource, 'createdAt' | 'removedAt'>
): void;
252 changes: 252 additions & 0 deletions deploy/selfhost/created-resources.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
#!/usr/bin/env node
// The record of cloud resources SAM's setup scripts created for one install, kept in the box
// state (`.state/created-resources.json`, mode 0600) so a teardown removes exactly those and
// nothing else. Provider-neutral: one entry per resource, whatever the cloud.
//
// {
// "format": "sam-created-resources/1",
// "resources": [{
// "cloud": "gcp" | "aws" | "azure" | ...,
// "kind": "kms-key" | "iam-binding" | "service-account" | ..., // the cloud's own terms
// "name": "<the cloud's identifier for it>", // unique per cloud+kind
// "attributes": { "project": "...", "role": "...", ... }, // strings, never secrets
// "createdBy": "gcp-bootstrap",
// "action": "created" | "reused", // reused: existed before; a teardown leaves it
// "createdAt": "<ISO time>",
// "removedAt": "<ISO time>" // set once a teardown removed it
// }]
// }
//
// Used by deploy/selfhost/gcp-bootstrap.sh:
// created-resources.mjs add <file> <cloud> <kind> <name> <created|reused> <createdBy> [k=v ...]
// created-resources.mjs list <file> <cloud> <createdBy> -> kind<TAB>name<TAB>action<TAB>removedAt
// created-resources.mjs removed <file> <cloud> <kind> <name>
import { randomUUID } from 'node:crypto';
import {
closeSync,
existsSync,
fsyncSync,
mkdirSync,
openSync,
readFileSync,
renameSync,
rmSync,
writeSync,
} from 'node:fs';
import { dirname } from 'node:path';

export const FORMAT = 'sam-created-resources/1';
const SECRETISH = /(secret|token|password|private|credential|key-material)/i;

export function readRecord(file) {
if (!existsSync(file)) return { format: FORMAT, resources: [] };
const parsed = JSON.parse(readFileSync(file, 'utf8'));
if (parsed?.format !== FORMAT || !Array.isArray(parsed.resources)) {
throw new Error(`${file} is not a ${FORMAT} record`);
}
const names = new Set();
for (const r of parsed.resources) {
if (
!r ||
typeof r.cloud !== 'string' ||
!r.cloud ||
typeof r.kind !== 'string' ||
!r.kind ||
typeof r.name !== 'string' ||
!r.name ||
typeof r.createdBy !== 'string' ||
!['created', 'reused'].includes(r.action) ||
(r.attributes !== undefined &&
(!r.attributes ||
typeof r.attributes !== 'object' ||
Array.isArray(r.attributes) ||
Object.values(r.attributes).some((v) => typeof v !== 'string')))
) {
throw new Error('invalid resource receipt; refusing ambiguous ownership');
}
const key = JSON.stringify([r.cloud, r.kind, r.name]);
if (names.has(key)) throw new Error('duplicate resource receipt; refusing ambiguous ownership');
names.add(key);
}
return parsed;
}

/** Bare GCP resource names may repeat across projects; never replace another project's proof. */
export function assertProject(file, project) {
for (const resource of readRecord(file).resources) {
if (resource.cloud === 'gcp' && !resource.removedAt && resource.attributes?.project !== project)
throw new Error(
'GCP receipt belongs to a different or unrecorded project; use a separate --state-dir and preserve the existing receipts'
);
}
}

function writeRecord(file, record) {
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
const tmp = `${file}.tmp-${process.pid}-${randomUUID()}`;
const fd = openSync(tmp, 'wx', 0o600);
try {
const data = Buffer.from(`${JSON.stringify(record, null, 2)}\n`);
let offset = 0;
while (offset < data.length) {
const count = writeSync(fd, data, offset, data.length - offset);
if (!count) throw new Error('Cannot persist resource receipt');
offset += count;
}
fsyncSync(fd);
} catch (error) {
rmSync(tmp, { force: true });
throw error;
} finally {
closeSync(fd);
}
renameSync(tmp, file);
const parent = openSync(dirname(file), 'r');
try {
fsyncSync(parent);
} finally {
closeSync(parent);
}
}

/** Absence was checked before an exact unconditional IAM mutation; retain that intent on retry. */
export function grantIntent(file, entry) {
const attrs = entry.attributes ?? {};
const required = [
'project',
'install',
'identity',
'pool',
'environment',
'installation',
'account',
'member',
'role',
'condition',
];
if (
entry.cloud !== 'gcp' ||
entry.createdBy !== 'gcp-bootstrap' ||
!['created', 'reused'].includes(entry.action) ||
!['iam-binding', 'service-account-iam-binding'].includes(entry.kind) ||
required.some((key) => typeof attrs[key] !== 'string' || !attrs[key]) ||
attrs.condition !== 'None'
)
throw new Error('Incomplete unconditional IAM grant intent');
const prior = readRecord(file).resources.find(
(r) => r.cloud === entry.cloud && r.kind === entry.kind && r.name === entry.name
);
if (prior && !prior.removedAt) {
if (
(prior.attributes?.grantPending &&
prior.attributes.grantPending !== 'unconditional-grant/1') ||
prior.createdBy !== entry.createdBy ||
required.some(
(key) =>
(prior.attributes?.[key] ?? (key === 'condition' ? 'None' : undefined)) !== attrs[key]
)
)
throw new Error('IAM grant identity or ownership scope changed; refusing intent adoption');
// A present preexisting grant stays reused. An observed absent grant is a new creation.
if (prior.action === 'created') entry.action = 'created';
}
entry.attributes = {
...attrs,
grantPending: entry.action === 'created' ? 'unconditional-grant/1' : '',
};
addResource(file, entry);
}

/**
* Adds or refreshes one entry. A live resource once recorded as created never becomes "reused".
* An entry a teardown removed that is recorded again exists again: it takes the new action and
* loses its removedAt, so a later teardown neither skips it as already removed nor deletes a
* resource this run only found (reused).
*/
export function addResource(file, entry, now = new Date()) {
for (const key of Object.keys(entry.attributes ?? {})) {
if (SECRETISH.test(key))
throw new Error(`refusing to record attribute ${key}: no secrets here`);
}
const record = readRecord(file);
const existing = record.resources.find(
(r) => r.cloud === entry.cloud && r.kind === entry.kind && r.name === entry.name
);
if (existing) {
const replaced =
existing.attributes?.identity &&
entry.attributes?.identity &&
existing.attributes.identity !== entry.attributes.identity;
if (
!existing.removedAt &&
!replaced &&
['install', 'installation', 'environment'].some(
(key) =>
existing.attributes?.[key] &&
entry.attributes?.[key] &&
existing.attributes[key] !== entry.attributes[key]
)
) {
throw new Error('resource ownership scope changed; refusing to adopt an existing receipt');
}
if (existing.removedAt || replaced) {
Object.assign(existing, { action: entry.action, createdAt: now.toISOString() });
delete existing.removedAt;
} else if (existing.action !== 'created') {
existing.action = entry.action;
}
existing.attributes = { ...existing.attributes, ...entry.attributes };
} else {
record.resources.push({ ...entry, createdAt: now.toISOString() });
}
writeRecord(file, record);
}

export function markRemoved(file, cloud, kind, name, now = new Date()) {
const record = readRecord(file);
const entry = record.resources.find(
(r) => r.cloud === cloud && r.kind === kind && r.name === name
);
if (!entry) throw new Error(`${cloud} ${kind} ${name} is not in ${file}`);
entry.removedAt = now.toISOString();
writeRecord(file, record);
}

if (import.meta.url === `file://${process.argv[1]}`) {
const [command, file, ...rest] = process.argv.slice(2);
try {
if (command === 'assert-project') {
const [project] = rest;
if (!project) throw new Error('assert-project requires a GCP project');
assertProject(file, project);
} else if (command === 'add' || command === 'grant-intent') {
const [cloud, kind, name, action, createdBy, ...pairs] = rest;
if (!cloud || !kind || !name || !['created', 'reused'].includes(action) || !createdBy) {
throw new Error(
'usage: add <file> <cloud> <kind> <name> <created|reused> <createdBy> [k=v ...]'
);
}
const attributes = Object.fromEntries(
pairs.map((pair) => [pair.slice(0, pair.indexOf('=')), pair.slice(pair.indexOf('=') + 1)])
);
const entry = { cloud, kind, name, attributes, createdBy, action };
if (command === 'grant-intent') grantIntent(file, entry);
else addResource(file, entry);
} else if (command === 'list') {
const [cloud, createdBy] = rest;
for (const r of readRecord(file).resources) {
if (r.cloud === cloud && r.createdBy === createdBy) {
process.stdout.write(`${r.kind}\t${r.name}\t${r.action}\t${r.removedAt ?? ''}\n`);
}
}
} else if (command === 'removed') {
const [cloud, kind, name] = rest;
markRemoved(file, cloud, kind, name);
} else {
throw new Error('usage: created-resources.mjs add|list|removed <file> ...');
}
} catch (error) {
process.stderr.write(`created-resources: ${error.message}\n`);
process.exit(1);
}
}
12 changes: 10 additions & 2 deletions deploy/selfhost/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
# `docker compose build` (or when the image does not exist yet); `pnpm selfhost:upgrade` rebuilds
# a service only when its build inputs changed. The pinned celld version must match CELLD_VERSION
# in scripts/selfhost/versions.ts, which the deploy script uses for `celld deploy`.
name: sam-selfhost
name: ${COMPOSE_PROJECT_NAME:?Set the installation-specific project printed by selfhost:deploy --init}

services:
celld:
Expand Down Expand Up @@ -412,7 +412,15 @@ services:
volumes:
- objectstore-data:/data
healthcheck:
test: ['CMD', 'mc', 'ready', 'local']
test:
[
'CMD',
'curl',
'--fail',
'--silent',
'--show-error',
'http://127.0.0.1:${OBJECTSTORE_PORT:-9000}/minio/health/ready',
]
interval: 5s
retries: 30
stop_grace_period: 30s
Expand Down
Loading
Loading