From 878fd5b402760c3c8d889b28e2a62d5b713a163a Mon Sep 17 00:00:00 2001 From: Helix the Red <355572797+helix-red@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:14:15 -0700 Subject: [PATCH 01/38] feat: localized registry index views and declared default locales (#4754) * feat(registry): pre-localize index subscriptions for a requested language db.subscribe accepts an optional language. Each distinct reader, OS compatibility and language combination is served by a lazily created, shared in-memory PatchDB mirror, as OS-version compatibility views already were; every LocaleString in that view resolves to the locale. Package version localization moves from for_device into Model::localize_for so package.get and the mirror share one implementation. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(registry): bound language views to bundled locales Unsupported languages resolve to the en_US view, so subscribers cannot create a mirror per arbitrary language string. set_locale and the registry share one supported_locale matcher, which no longer panics on an empty language; LocaleString::localize_for accepts an empty locale too (from helix-white's proposal). Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(registry): resolve view languages against the index's own locales A requested language now resolves to a locale that appears in the reader's visible index, else the en_US view, instead of to the locales StartOS bundles. Languages a package ships but StartOS lacks get their own view; private-package languages are only offered to readers who can see them. Localization and language discovery share one LocaleString traversal; the per-type DependencyMetadata/Description localizers it replaces are removed. best_locale generalizes set_locale's matcher over any locale set. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * perf(registry): track index locales instead of walking per subscribe IndexLocaleTracker loads the index's locales, grouped by package, at startup and recomputes them after each /index revision. Subscriptions resolve their language against the reader-visible part of that set without walking the index, keeping private-package languages hidden from readers who cannot see the package. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(registry): synchronize locale snapshots before subscription Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * fix(registry): wait for locale snapshots only for localized subscriptions Canonical subscriptions read the live database as before, so a locale tracker failure affects only subscriptions that request a language. IndexView::localized replaces the optional-language resolve. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * chore(registry): regenerate MCP catalog for db.subscribe language Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * feat: declared default locales for package and registry text LocaleString resolution is now, everywhere: the requested locale's exact or same-language translation, then the owner's declared default locale, then an arbitrary stored translation for data published before defaults existed (PatchDB does not preserve key order, so no stored order is meaningful). - PackageMetadata (manifest and registry index) gains defaultLocale. The SDK fills it from setupI18n's default language unless the manifest sets it explicitly. - The registry index gains defaultLocale for its own description, category names and OS release notes, set with info set-default-locale. - Registry language views: a language matching none of the reader's visible locales, even by language code, shares one default view in which each string resolves to its owner's default. - StartOS: dependency titles and the OS update cache use the owner's default; the UI and brochure marketplace pass the package's or registry's default to the shared localizeFor, which mirrors the backend rule. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * Proposed changes for #4754 Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * chore: format sync and regenerate bindings for adopted review changes Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * feat(sdk)!: buildManifest takes the package's i18n for its default locale setupI18n's result carries its default language, and buildManifest requires it as a fourth argument, recording it as defaultLocale. The default comes from the package's own i18n rather than shared SDK state, and packages that have not adopted it fail to typecheck until they pass i18n. SDK 5.0.0 with an Important notice for upgrading packages. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * feat(sdk)!: buildManifest takes named arguments buildManifest({ versionGraph, manifest, dependencies, i18n }) replaces the positional form, which grew to four arguments; the 5.0.0 notice, fragment, template and guide use it. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * Proposed changes for #4754 Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol --------- Co-authored-by: helix-white <267227783+helix-a@users.noreply.github.com> --- Cargo.lock | 2 +- .../src/app/services/api.fixures.ts | 1 + .../src/app/services/localize.ts | 21 +- .../src/app/services/marketplace.service.ts | 4 +- .../patch-added-manifest-default-locale.md | 5 + ...art-cli-registry-info-set-default-locale.1 | 19 ++ .../start-cli/man/start-cli-registry-info.1 | 3 + .../patch-changed-default-locale-fallback.md | 5 + projects/start-os/docs/src/cli-reference.md | 8 + projects/start-os/web/ui/scripts/ui.test.mjs | 36 ++- .../components/controls.component.ts | 2 +- .../marketplace/services/alerts.service.ts | 14 +- .../system/routes/general/update.component.ts | 4 +- .../portal/routes/updates/item.component.ts | 10 +- .../ui/src/app/services/api/api.fixures.ts | 1 + .../web/ui/src/app/services/api/mock-patch.ts | 1 + .../web/ui/src/app/services/os.service.ts | 1 + projects/start-registry/ARCHITECTURE.md | 20 +- projects/start-registry/Cargo.toml | 2 +- projects/start-registry/README.md | 2 +- ...nor-added-localized-index-subscriptions.md | 6 + .../start-registry-info-set-default-locale.1 | 19 ++ .../start-registry/man/start-registry-info.1 | 3 + projects/start-registry/man/start-registry.1 | 4 +- projects/start-sdk/ARCHITECTURE.md | 2 +- projects/start-sdk/README.md | 8 +- ...r-changed-build-manifest-default-locale.md | 5 + .../docs/package-template/package.json | 2 +- .../docs/package-template/startos/index.ts | 8 +- projects/start-sdk/docs/src/dependencies.md | 2 +- projects/start-sdk/docs/src/manifest.md | 7 +- projects/start-sdk/docs/src/shared-volumes.md | 2 +- projects/start-sdk/lib/i18n/index.ts | 10 +- .../start-sdk/lib/manifest/setupManifest.ts | 23 +- .../start-sdk/lib/test/setupManifest.test.ts | 95 +++++-- projects/start-sdk/package-lock.json | 4 +- projects/start-sdk/package.json | 2 +- projects/start-sdk/release-notes/5.0.0.md | 3 + projects/start-wrt/backend/ctrl/src/system.rs | 2 +- .../backend/ctrl/src/update/tests.rs | 5 +- .../crates/start-core/locales/i18n.yaml | 21 ++ shared-libs/crates/start-core/mcp-tools.json | 80 +++++- shared-libs/crates/start-core/src/bins/mod.rs | 15 +- shared-libs/crates/start-core/src/lib.rs | 13 + .../crates/start-core/src/registry/context.rs | 6 + .../crates/start-core/src/registry/db.rs | 25 +- .../start-core/src/registry/device_info.rs | 2 +- .../crates/start-core/src/registry/info.rs | 49 ++++ .../crates/start-core/src/registry/locales.rs | 257 ++++++++++++++++++ .../crates/start-core/src/registry/mirror.rs | 157 +++++++---- .../registry/mirror/tests/compatibility.rs | 193 ++++++++++++- .../crates/start-core/src/registry/mod.rs | 34 +++ .../src/registry/os/ingestion_tests.rs | 2 +- .../start-core/src/registry/os/version/mod.rs | 2 +- .../src/registry/package/category.rs | 2 +- .../start-core/src/registry/package/get.rs | 6 +- .../start-core/src/registry/package/index.rs | 84 ++++-- .../crates/start-core/src/registry/sync.rs | 34 ++- .../start-core/src/registry/sync/polling.rs | 1 + .../start-core/src/registry/sync/tests.rs | 1 + .../src/registry/sync/tests/default_locale.rs | 89 ++++++ .../crates/start-core/src/s9pk/v2/compat.rs | 1 + .../crates/start-core/src/s9pk/v2/manifest.rs | 86 ++++-- .../src/service/effects/dependency.rs | 85 +++++- .../start-core/src/version/release_notes.rs | 2 +- .../src/components/about.component.ts | 4 +- .../src/components/dependency.component.ts | 8 +- .../src/components/marketplace.component.ts | 15 +- .../src/components/release-notes.component.ts | 7 +- .../src/components/tile.component.ts | 4 +- .../shared/scripts/localize.test.mjs | 15 + .../shared/src/i18n/i18n.service.ts | 9 +- .../shared/src/i18n/localize.pipe.ts | 5 +- .../ts-modules/shared/src/i18n/localize.ts | 25 ++ .../lib/osBindings/rpc/effects.schemas.ts | 11 + .../lib/osBindings/rpc/registry.schemas.ts | 97 ++++++- .../start-core/lib/osBindings/rpc/registry.ts | 3 + .../lib/osBindings/rpc/start-os.schemas.ts | 100 ++++++- .../start-core/lib/osBindings/rpc/start-os.ts | 3 + .../lib/osBindings/types.schemas.ts | 80 +++++- .../start-core/lib/osBindings/types.ts | 6 + 81 files changed, 1749 insertions(+), 263 deletions(-) create mode 100644 projects/start-cli/changelog/patch-added-manifest-default-locale.md create mode 100644 projects/start-cli/man/start-cli-registry-info-set-default-locale.1 create mode 100644 projects/start-os/changelog/patch-changed-default-locale-fallback.md create mode 100644 projects/start-registry/changelog/minor-added-localized-index-subscriptions.md create mode 100644 projects/start-registry/man/start-registry-info-set-default-locale.1 create mode 100644 projects/start-sdk/changelog/major-changed-build-manifest-default-locale.md create mode 100644 projects/start-sdk/release-notes/5.0.0.md create mode 100644 shared-libs/crates/start-core/src/registry/locales.rs create mode 100644 shared-libs/crates/start-core/src/registry/sync/tests/default_locale.rs create mode 100644 shared-libs/ts-modules/shared/scripts/localize.test.mjs create mode 100644 shared-libs/ts-modules/shared/src/i18n/localize.ts diff --git a/Cargo.lock b/Cargo.lock index 4a02e81a10..af82833993 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8535,7 +8535,7 @@ dependencies = [ [[package]] name = "start-registry" -version = "1.6.0" +version = "1.7.0" dependencies = [ "mimalloc", "start-core", diff --git a/projects/brochure-marketplace/src/app/services/api.fixures.ts b/projects/brochure-marketplace/src/app/services/api.fixures.ts index 6a387c44ee..a86266c6a8 100644 --- a/projects/brochure-marketplace/src/app/services/api.fixures.ts +++ b/projects/brochure-marketplace/src/app/services/api.fixures.ts @@ -15,6 +15,7 @@ const mockDescription = { export namespace Mock { export const RegistryInfo: T.RegistryInfo = { + defaultLocale: 'en_US', trustSigners: {}, name: 'Start9 Registry', icon: REGISTRY_ICON, diff --git a/projects/brochure-marketplace/src/app/services/localize.ts b/projects/brochure-marketplace/src/app/services/localize.ts index 03c8f6a0d1..480f79f6be 100644 --- a/projects/brochure-marketplace/src/app/services/localize.ts +++ b/projects/brochure-marketplace/src/app/services/localize.ts @@ -13,7 +13,10 @@ import { T } from '@start9labs/start-core' * the guarantee even if a component forgets to localize, and is the hook a * future in-app language selector re-runs to re-localize without re-fetching. */ -export type Localize = (value: T.LocaleString) => string +export type Localize = ( + value: T.LocaleString, + defaultLocale?: string | null, +) => string export function localizeRegistryInfo( info: T.RegistryInfo, @@ -23,7 +26,7 @@ export function localizeRegistryInfo( ...info, categories: mapValues(info.categories, c => ({ ...c, - name: localize(c.name), + name: localize(c.name, info.defaultLocale), })), } } @@ -39,7 +42,7 @@ export function localizePackageRes( res.otherVersions && mapValues(res.otherVersions, v => ({ ...v, - releaseNotes: localize(v.releaseNotes), + releaseNotes: localize(v.releaseNotes, v.defaultLocale), })), } } @@ -51,15 +54,17 @@ function localizeVersionInfo( return { ...v, description: { - short: localize(v.description.short), - long: localize(v.description.long), + short: localize(v.description.short, v.defaultLocale), + long: localize(v.description.long, v.defaultLocale), }, - releaseNotes: localize(v.releaseNotes), + releaseNotes: localize(v.releaseNotes, v.defaultLocale), dependencyMetadata: mapValues(v.dependencyMetadata, d => ({ ...d, - title: d.title == null ? d.title : localize(d.title), + title: d.title == null ? d.title : localize(d.title, v.defaultLocale), description: - d.description == null ? d.description : localize(d.description), + d.description == null + ? d.description + : localize(d.description, v.defaultLocale), })), } } diff --git a/projects/brochure-marketplace/src/app/services/marketplace.service.ts b/projects/brochure-marketplace/src/app/services/marketplace.service.ts index efda31c747..d74e8942f3 100644 --- a/projects/brochure-marketplace/src/app/services/marketplace.service.ts +++ b/projects/brochure-marketplace/src/app/services/marketplace.service.ts @@ -59,8 +59,8 @@ export class MarketplaceService extends AbstractMarketplaceService { // Collapse LocaleString metadata to the active locale as it enters the app — // see localize.ts for why this static site must do it client-side. - private readonly localize: Localize = value => - this.i18nService.localize(value) + private readonly localize: Localize = (value, defaultLocale) => + this.i18nService.localize(value, defaultLocale) // Emits the url of a registry that failed to load (unreachable / CORS). readonly registryError$ = new Subject() diff --git a/projects/start-cli/changelog/patch-added-manifest-default-locale.md b/projects/start-cli/changelog/patch-added-manifest-default-locale.md new file mode 100644 index 0000000000..535a49fe7d --- /dev/null +++ b/projects/start-cli/changelog/patch-added-manifest-default-locale.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Packed s9pks keep the manifest's default locale. diff --git a/projects/start-cli/man/start-cli-registry-info-set-default-locale.1 b/projects/start-cli/man/start-cli-registry-info-set-default-locale.1 new file mode 100644 index 0000000000..d1496200b3 --- /dev/null +++ b/projects/start-cli/man/start-cli-registry-info-set-default-locale.1 @@ -0,0 +1,19 @@ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' +.TH start-cli-registry-info-set-default-locale 1 "set-default-locale " +.SH NAME +start\-cli\-registry\-info\-set\-default\-locale \- Set the locale the registry\*(Aqs own text falls back to +.SH SYNOPSIS +\fBstart\-cli registry info set\-default\-locale\fR [\fB\-\-clear\fR] [\fB\-h\fR|\fB\-\-help\fR] [\fIDEFAULT_LOCALE\fR] +.SH DESCRIPTION +Set the locale the registry\*(Aqs own text falls back to +.SH OPTIONS +.TP +\fB\-\-clear\fR +Remove the registry default locale +.TP +\fB\-h\fR, \fB\-\-help\fR +Print help +.TP +[\fIDEFAULT_LOCALE\fR] +Locale the registry\*(Aqs own text falls back to, such as en_US diff --git a/projects/start-cli/man/start-cli-registry-info.1 b/projects/start-cli/man/start-cli-registry-info.1 index 28085f6088..53cfd545a8 100644 --- a/projects/start-cli/man/start-cli-registry-info.1 +++ b/projects/start-cli/man/start-cli-registry-info.1 @@ -16,6 +16,9 @@ View or edit registry information Print help .SH SUBCOMMANDS .TP +start\-cli\-registry\-info\-set\-default\-locale(1) +Set the locale the registry\*(Aqs own text falls back to +.TP start\-cli\-registry\-info\-set\-description(1) Set the registry description .TP diff --git a/projects/start-os/changelog/patch-changed-default-locale-fallback.md b/projects/start-os/changelog/patch-changed-default-locale-fallback.md new file mode 100644 index 0000000000..d54317bf3e --- /dev/null +++ b/projects/start-os/changelog/patch-changed-default-locale-fallback.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- When a service's description, release notes or alerts aren't translated into your language, StartOS shows the service's own default language instead of an arbitrary one. diff --git a/projects/start-os/docs/src/cli-reference.md b/projects/start-os/docs/src/cli-reference.md index 32a8cfb6ea..2ee3b01696 100644 --- a/projects/start-os/docs/src/cli-reference.md +++ b/projects/start-os/docs/src/cli-reference.md @@ -976,6 +976,14 @@ Set the registry's description (markdown), shown above its services in the marke Over RPC, pass `null` in the setter's `description` field to clear it; a value sets it. +### `start-cli registry info set-default-locale [DEFAULT_LOCALE] [--clear]` + +Set the locale, such as `en_US`, that the registry's own description, category names and OS release notes fall back to when a reader's language is missing. Supply either `DEFAULT_LOCALE` or `--clear`, but not both. + +- `--clear` — Remove the registry's default locale + +Over RPC, pass `null` in the setter's `defaultLocale` field to clear it; a value sets it. + ### `start-cli registry info set-trust-signers [SIGNER...]` Select which existing signers the registry offers to StartOS servers for package trust. Run it without signer IDs to clear the selection. See [Trusted Keys](trusted-keys.md#keys-from-registries) for how StartOS treats offered keys. diff --git a/projects/start-os/web/ui/scripts/ui.test.mjs b/projects/start-os/web/ui/scripts/ui.test.mjs index a9fa17fdcc..230ae6e3ba 100644 --- a/projects/start-os/web/ui/scripts/ui.test.mjs +++ b/projects/start-os/web/ui/scripts/ui.test.mjs @@ -300,8 +300,8 @@ const catalog = { '0.4.0.3': { releaseNotes: 'newer', squashfs }, } const candidates = [ - { version: '0.4.0.4', notes: 'newest', squashfs }, - { version: '0.4.0.3', notes: 'newer', squashfs }, + { version: '0.4.0.4', notes: 'newest', squashfs, defaultLocale: 'pl_PL' }, + { version: '0.4.0.3', notes: 'newer', squashfs, defaultLocale: 'pl_PL' }, ] const state = version => ({ registryCache: {}, @@ -513,7 +513,7 @@ function fixture(t, cachedVersion, providers = []) { versions = catalog, { registry = 'https://registry.test/', status = 'connected' } = {}, ) { - osUpdateCache = { registry, versions, status } + osUpdateCache = { registry, versions, defaultLocale: 'pl_PL', status } source.next([ { id: ++revision, @@ -1090,7 +1090,14 @@ test('a registry switch releases a load waiting for the previous source without { registry: 'https://second.test' }, ) await f.os.checkForUpdates() - assert.equal(f.os.updateCandidates()[0].notes, 'selected') + assert.deepEqual(f.os.updateCandidates(), [ + { + version: '0.4.0.3', + notes: 'selected', + squashfs, + defaultLocale: 'pl_PL', + }, + ]) }) test('without a cache, load waits for the first live state', async t => { @@ -1137,7 +1144,12 @@ test('strictly newer candidates sort descending; offline cache remains readable; assert.equal(f.requests.length, 0) await f.load({ '0.4.0.5': { releaseNotes: 'refreshed', squashfs } }) assert.deepEqual(f.os.updateCandidates(), [ - { version: '0.4.0.5', notes: 'refreshed', squashfs }, + { + version: '0.4.0.5', + notes: 'refreshed', + squashfs, + defaultLocale: 'pl_PL', + }, ]) }) @@ -1150,7 +1162,12 @@ test('a different image at the installed version is offered and submitted', asyn }) assert.deepEqual(f.os.updateCandidates(), [ ...candidates, - { version: '0.4.0.2', notes: 'next image', squashfs }, + { + version: '0.4.0.2', + notes: 'next image', + squashfs, + defaultLocale: 'pl_PL', + }, ]) await f.load({ @@ -1211,7 +1228,12 @@ test('a same-version image is offered from the synced catalog without a manual c '0.4.0.2': { releaseNotes: 'next image', squashfs, gitHash: nextGitHash }, }) assert.deepEqual(f.os.updateCandidates(), [ - { version: '0.4.0.2', notes: 'next image', squashfs }, + { + version: '0.4.0.2', + notes: 'next image', + squashfs, + defaultLocale: 'pl_PL', + }, ]) assert.equal(f.availability.at(-1), true) f.build(nextGitHash) diff --git a/projects/start-os/web/ui/src/app/routes/portal/routes/marketplace/components/controls.component.ts b/projects/start-os/web/ui/src/app/routes/portal/routes/marketplace/components/controls.component.ts index aec90f432f..d108da56df 100644 --- a/projects/start-os/web/ui/src/app/routes/portal/routes/marketplace/components/controls.component.ts +++ b/projects/start-os/web/ui/src/app/routes/portal/routes/marketplace/components/controls.component.ts @@ -159,7 +159,7 @@ export class MarketplaceControlsComponent { if ( !this.file() && !(await this.alerts.alertPreDownload( - this.pkg().preDownloadAlert, + this.pkg(), localPkg ? getManifest(localPkg).version : null, )) ) diff --git a/projects/start-os/web/ui/src/app/routes/portal/routes/marketplace/services/alerts.service.ts b/projects/start-os/web/ui/src/app/routes/portal/routes/marketplace/services/alerts.service.ts index 4cf552973d..0edf88b38d 100644 --- a/projects/start-os/web/ui/src/app/routes/portal/routes/marketplace/services/alerts.service.ts +++ b/projects/start-os/web/ui/src/app/routes/portal/routes/marketplace/services/alerts.service.ts @@ -20,6 +20,7 @@ import { MarketplaceService } from 'src/app/services/marketplace.service' type PreDownloadDialogData = TuiConfirmData & { content: PolymorpheusComponent message: T.LocaleString + defaultLocale?: string | null } @Component({ @@ -28,7 +29,9 @@ type PreDownloadDialogData = TuiConfirmData & {
`, @@ -41,9 +44,8 @@ type PreDownloadDialogData = TuiConfirmData & { ], }) class PreDownloadMessage { - protected readonly message = + protected readonly data = injectContext>().data - .message } const PRE_DOWNLOAD_MESSAGE = new PolymorpheusComponent(PreDownloadMessage) @@ -86,7 +88,10 @@ export class MarketplaceAlertsService { } async alertPreDownload( - alert: T.PreDownloadAlert | null | undefined, + { + preDownloadAlert: alert, + defaultLocale, + }: Pick, sourceVersion: string | null, ): Promise { if ( @@ -100,6 +105,7 @@ export class MarketplaceAlertsService { const data: PreDownloadDialogData = { content: PRE_DOWNLOAD_MESSAGE, message: alert.message, + defaultLocale, yes: 'Continue', no: 'Cancel', } diff --git a/projects/start-os/web/ui/src/app/routes/portal/routes/system/routes/general/update.component.ts b/projects/start-os/web/ui/src/app/routes/portal/routes/system/routes/general/update.component.ts index 84983f4001..07faf0f0c2 100644 --- a/projects/start-os/web/ui/src/app/routes/portal/routes/system/routes/general/update.component.ts +++ b/projects/start-os/web/ui/src/app/routes/portal/routes/system/routes/general/update.component.ts @@ -40,7 +40,9 @@ import { TRUSTED_KEYS_LINK } from '../../system.const' }
} diff --git a/projects/start-os/web/ui/src/app/routes/portal/routes/updates/item.component.ts b/projects/start-os/web/ui/src/app/routes/portal/routes/updates/item.component.ts index a36fbddb9f..fa41723a9c 100644 --- a/projects/start-os/web/ui/src/app/routes/portal/routes/updates/item.component.ts +++ b/projects/start-os/web/ui/src/app/routes/portal/routes/updates/item.component.ts @@ -182,7 +182,12 @@ import UpdatesComponent from './updates.component'

@@ -364,12 +369,11 @@ export class UpdatesItemComponent { if (trust && !(await this.alerts.alertUntrusted())) return const pkg = this.item() - const { preDownloadAlert } = pkg const url = this.parent.current()?.url || '' if ( !(await this.alerts.alertPreDownload( - preDownloadAlert, + pkg, this.local().stateInfo.manifest.version, )) ) { diff --git a/projects/start-os/web/ui/src/app/services/api/api.fixures.ts b/projects/start-os/web/ui/src/app/services/api/api.fixures.ts index 91a74f3194..c4696f5e38 100644 --- a/projects/start-os/web/ui/src/app/services/api/api.fixures.ts +++ b/projects/start-os/web/ui/src/app/services/api/api.fixures.ts @@ -290,6 +290,7 @@ export namespace Mock { } export const RegistryInfo: T.RegistryInfo = { + defaultLocale: 'en_US', trustSigners: { 'start9-signer': { name: 'Start9', diff --git a/projects/start-os/web/ui/src/app/services/api/mock-patch.ts b/projects/start-os/web/ui/src/app/services/api/mock-patch.ts index 4f94f9b481..6816e71d34 100644 --- a/projects/start-os/web/ui/src/app/services/api/mock-patch.ts +++ b/projects/start-os/web/ui/src/app/services/api/mock-patch.ts @@ -97,6 +97,7 @@ export function mockOsUpdateCache( versions: sameUrl(registry, defaultRegistries.community) ? {} : Mock.RegistryOSUpdate, + defaultLocale: 'en_US', status: 'connected', } } diff --git a/projects/start-os/web/ui/src/app/services/os.service.ts b/projects/start-os/web/ui/src/app/services/os.service.ts index 1f95531096..6c04beb201 100644 --- a/projects/start-os/web/ui/src/app/services/os.service.ts +++ b/projects/start-os/web/ui/src/app/services/os.service.ts @@ -64,6 +64,7 @@ export class OSService { .map(([version, info]) => ({ version, notes: info.releaseNotes, + defaultLocale: cache?.defaultLocale, squashfs: info.squashfs, })) }), diff --git a/projects/start-registry/ARCHITECTURE.md b/projects/start-registry/ARCHITECTURE.md index ec83ef1f81..8174b7ba14 100644 --- a/projects/start-registry/ARCHITECTURE.md +++ b/projects/start-registry/ARCHITECTURE.md @@ -58,12 +58,30 @@ Subcommands (same module), each available over RPC and to the `start-registry` C ### Registry index subscriptions -The public `db.subscribe` RPC accepts optional `pointer` and `osVersion` parameters. The pointer +The public `db.subscribe` RPC accepts optional `pointer`, `osVersion` and `language` parameters. The pointer may select `/index` or any descendant; omitting it or passing `null` selects `/index`. Without `rpcstream` opt-in, the response contains an initial `{ id, value }` dump and a continuation `guid`. Connecting to `/rpc/v2/` streams revisions relative to the selected subtree. This contract also applies to ordinary calls on the shared WebSocket. +`language` resolves every `LocaleString` in the view with `LocaleString::localize_for`: +the exact or same-language translation, else the owner's declared default locale +(`PackageMetadata::default_locale` for package text, `FullIndex::default_locale` for +registry text, set by `info set-default-locale`), else an arbitrary stored one. The +requested language is first matched against the locales in the reader's visible index +(`best_locale`); a language matching none of them shares the default view, where +every string resolves to its owner's default, so requests cannot create views beyond +the index's own languages. +`IndexLocaleTracker` (`registry/locales.rs`) holds those locales per package. It +captures the database and locale metadata together, recomputing the locales when +`/index` changes. A subscription with `language` waits for a snapshot at or after its initiating +database revision and resolves both reader access and language against that snapshot, +without walking the index. Root revisions also advance snapshot freshness when +permissions outside `/index` change. Each distinct reader, `osVersion` +compatibility and `language` combination is an `IndexView` served by a lazily +created in-memory PatchDB mirror (`registry/mirror.rs`), shared by its +subscribers and dropped with the last of them. + With `rpcstream: "1.0"` on `/rpc/v2`, the same method returns the dump directly as its initiating result and sends subsequent `Revision` events under that request ID. Closing a stream releases its subscription; ordinary calls and other subscriptions retain the connection. diff --git a/projects/start-registry/Cargo.toml b/projects/start-registry/Cargo.toml index 655a512c10..8eabfb7581 100644 --- a/projects/start-registry/Cargo.toml +++ b/projects/start-registry/Cargo.toml @@ -3,7 +3,7 @@ edition = "2024" license = "MIT" name = "start-registry" repository = "https://github.com/Start9Labs/start-technologies" -version = "1.6.0" # VERSION_BUMP +version = "1.7.0" # VERSION_BUMP [[bin]] name = "registrybox" diff --git a/projects/start-registry/README.md b/projects/start-registry/README.md index 1503a7c1be..14b96aadd7 100644 --- a/projects/start-registry/README.md +++ b/projects/start-registry/README.md @@ -97,7 +97,7 @@ Configuration is read from CLI flags and a config file (`-c `; default sea | `-c, --config ` | config file | | `--mirror-of ` | mirror another registry's index (read-only index) | -Clients synchronize registry metadata through `db.subscribe`: `rpcstream` opt-in uses the shared `/rpc/v2` socket, while ordinary requests retain the GUID WebSocket continuation. StartOS authenticates and encrypts this shared connection through signed ephemeral DH. Streaming requires encrypted admission and `rpcstream`, with the client's selected URL host configured on the registry. A legacy HTTP 200 response without upgrading, or HTTP 404/405/501, selects signed HTTP polling every 15 minutes; each cycle retries upgrade support. Polls retrieve full package versions/revisions, registry info and the selected OS index through the same cache/trust owners. Authorization, transport and failed encrypted admission errors never downgrade. A subscription's optional `osVersion` selects a lazily shared backward-compatible index view; omitted versions retain the canonical format. StartOS maintains package, signer, and OS-update caches independently of open browser sessions. OS releases marked `security` generate notifications on compatible StartOS servers using that registry for updates. +Clients synchronize registry metadata through `db.subscribe`: `rpcstream` opt-in uses the shared `/rpc/v2` socket, while ordinary requests retain the GUID WebSocket continuation. StartOS authenticates and encrypts this shared connection through signed ephemeral DH. Streaming requires encrypted admission and `rpcstream`, with the client's selected URL host configured on the registry. A legacy HTTP 200 response without upgrading, or HTTP 404/405/501, selects signed HTTP polling every 15 minutes; each cycle retries upgrade support. Polls retrieve full package versions/revisions, registry info and the selected OS index through the same cache/trust owners. Authorization, transport and failed encrypted admission errors never downgrade. A subscription's optional `osVersion` selects a lazily shared backward-compatible index view, and its optional `language` a lazily shared view with every translated field resolved to that locale; omitting them retains the canonical format. StartOS maintains package, signer, and OS-update caches independently of open browser sessions. OS releases marked `security` generate notifications on compatible StartOS servers using that registry for updates. ## Mirroring another registry diff --git a/projects/start-registry/changelog/minor-added-localized-index-subscriptions.md b/projects/start-registry/changelog/minor-added-localized-index-subscriptions.md new file mode 100644 index 0000000000..b67475dc20 --- /dev/null +++ b/projects/start-registry/changelog/minor-added-localized-index-subscriptions.md @@ -0,0 +1,6 @@ +--- +release-notes: false +--- + +- Index subscriptions accept an optional `language` and receive registry, category, package and OS text already translated for that locale. A language with no translation falls back to each package's declared default locale. +- `start-registry info set-default-locale` sets the locale the registry's own text falls back to. diff --git a/projects/start-registry/man/start-registry-info-set-default-locale.1 b/projects/start-registry/man/start-registry-info-set-default-locale.1 new file mode 100644 index 0000000000..f94db642d4 --- /dev/null +++ b/projects/start-registry/man/start-registry-info-set-default-locale.1 @@ -0,0 +1,19 @@ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' +.TH start-registry-info-set-default-locale 1 "set-default-locale " +.SH NAME +start\-registry\-info\-set\-default\-locale \- Set the locale the registry\*(Aqs own text falls back to +.SH SYNOPSIS +\fBstart\-registry info set\-default\-locale\fR [\fB\-\-clear\fR] [\fB\-h\fR|\fB\-\-help\fR] [\fIDEFAULT_LOCALE\fR] +.SH DESCRIPTION +Set the locale the registry\*(Aqs own text falls back to +.SH OPTIONS +.TP +\fB\-\-clear\fR +Remove the registry default locale +.TP +\fB\-h\fR, \fB\-\-help\fR +Print help +.TP +[\fIDEFAULT_LOCALE\fR] +Locale the registry\*(Aqs own text falls back to, such as en_US diff --git a/projects/start-registry/man/start-registry-info.1 b/projects/start-registry/man/start-registry-info.1 index f124017230..16f1ffca41 100644 --- a/projects/start-registry/man/start-registry-info.1 +++ b/projects/start-registry/man/start-registry-info.1 @@ -16,6 +16,9 @@ View or edit registry information Print help .SH SUBCOMMANDS .TP +start\-registry\-info\-set\-default\-locale(1) +Set the locale the registry\*(Aqs own text falls back to +.TP start\-registry\-info\-set\-description(1) Set the registry description .TP diff --git a/projects/start-registry/man/start-registry.1 b/projects/start-registry/man/start-registry.1 index 1c1486bc08..76de40be1c 100644 --- a/projects/start-registry/man/start-registry.1 +++ b/projects/start-registry/man/start-registry.1 @@ -1,6 +1,6 @@ .ie \n(.g .ds Aq \(aq .el .ds Aq ' -.TH start-registry 1 "start-registry 1.6.0" +.TH start-registry 1 "start-registry 1.7.0" .SH NAME start\-registry .SH SYNOPSIS @@ -72,4 +72,4 @@ Commands related to OS assets and versions start\-registry\-package(1) Commands to index, add, or get packages .SH VERSION -v1.6.0 +v1.7.0 diff --git a/projects/start-sdk/ARCHITECTURE.md b/projects/start-sdk/ARCHITECTURE.md index 27fcad91a6..25288806a1 100644 --- a/projects/start-sdk/ARCHITECTURE.md +++ b/projects/start-sdk/ARCHITECTURE.md @@ -406,7 +406,7 @@ const manifest = setupManifest({ // ... }) -export default buildManifest(versionGraph, manifest, dependencies) +export default buildManifest({ versionGraph, manifest, dependencies, i18n }) ``` `buildManifest()` finalizes the manifest with the current SDK version, OS version compatibility, migration version ranges, and dependency definitions from the same builder that runs during init. diff --git a/projects/start-sdk/README.md b/projects/start-sdk/README.md index 74a3c5488d..52681aba2d 100644 --- a/projects/start-sdk/README.md +++ b/projects/start-sdk/README.md @@ -25,6 +25,7 @@ It lives at `projects/start-sdk/` inside the [start-technologies monorepo](https ```typescript import { setupManifest, buildManifest, Dependencies } from '@start9labs/start-sdk' import { versionGraph } from './versions' +import { i18n } from './i18n' const manifest = setupManifest({ id: 'my-service', @@ -33,7 +34,12 @@ const manifest = setupManifest({ // ... }) -export default buildManifest(versionGraph, manifest, Dependencies.of()) +export default buildManifest({ + versionGraph, + manifest, + dependencies: Dependencies.of(), + i18n, +}) ``` The primary entry point is the `StartSdk` facade: diff --git a/projects/start-sdk/changelog/major-changed-build-manifest-default-locale.md b/projects/start-sdk/changelog/major-changed-build-manifest-default-locale.md new file mode 100644 index 0000000000..ddfcd65afb --- /dev/null +++ b/projects/start-sdk/changelog/major-changed-build-manifest-default-locale.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- `buildManifest` takes named arguments, `{ versionGraph, manifest, dependencies, i18n }`, and now requires the package's `setupI18n` result. Its default language becomes the manifest's `defaultLocale`, the locale StartOS and registries fall back to when a reader's language is missing. diff --git a/projects/start-sdk/docs/package-template/package.json b/projects/start-sdk/docs/package-template/package.json index c73a1867d8..fed3cb9cc9 100644 --- a/projects/start-sdk/docs/package-template/package.json +++ b/projects/start-sdk/docs/package-template/package.json @@ -1,7 +1,7 @@ { "name": "{{id}}-startos", "dependencies": { - "@start9labs/start-sdk": "4.2.0" + "@start9labs/start-sdk": "5.0.0" }, "overrides": { "@start9labs/start-sdk": "$@start9labs/start-sdk" diff --git a/projects/start-sdk/docs/package-template/startos/index.ts b/projects/start-sdk/docs/package-template/startos/index.ts index e8825763a1..d22745b167 100644 --- a/projects/start-sdk/docs/package-template/startos/index.ts +++ b/projects/start-sdk/docs/package-template/startos/index.ts @@ -9,4 +9,10 @@ import { buildManifest } from '@start9labs/start-sdk' import { manifest as sdkManifest } from './manifest' import { versionGraph } from './versions' import { dependencies } from './dependencies' -export const manifest = buildManifest(versionGraph, sdkManifest, dependencies) +import { i18n } from './i18n' +export const manifest = buildManifest({ + versionGraph, + manifest: sdkManifest, + dependencies, + i18n, +}) diff --git a/projects/start-sdk/docs/src/dependencies.md b/projects/start-sdk/docs/src/dependencies.md index 1423f62348..e5e28abce7 100644 --- a/projects/start-sdk/docs/src/dependencies.md +++ b/projects/start-sdk/docs/src/dependencies.md @@ -19,7 +19,7 @@ const bitcoin = sdk.Dependency.required('bitcoind', { export const dependencies = sdk.Dependencies.of().addDependency(bitcoin) ``` -Pass `dependencies` to `buildManifest(versionGraph, sdkManifest, dependencies)` in `startos/index.ts` and to `sdk.setupInit(..., dependencies, ...)` in `startos/init/index.ts`. +Pass `dependencies` to `buildManifest({ versionGraph, manifest, dependencies, i18n })` in `startos/index.ts` and to `sdk.setupInit(..., dependencies, ...)` in `startos/init/index.ts`. The base is serializable at pack time, without effects: every dependency needs a description (which may be `null`), inline title and icon, version range, kind, and health checks when `kind` is `running`. Write `'*'` when any version is accepted. Name multi-flavor dependencies generically: for `bitcoind`, use **Bitcoin**, not Bitcoin Core or Bitcoin Knots. The base is the loosest requirement the service accepts in any configuration. diff --git a/projects/start-sdk/docs/src/manifest.md b/projects/start-sdk/docs/src/manifest.md index c9c8f493eb..dd1eeb6f96 100644 --- a/projects/start-sdk/docs/src/manifest.md +++ b/projects/start-sdk/docs/src/manifest.md @@ -27,6 +27,11 @@ export const long = { } ``` +If neither the requested locale nor a same-language translation is available, +StartOS and registries use the package's default locale: the `DEFAULT_LANG` given +to `setupI18n` in `startos/i18n`. `buildManifest()` reads it from the `i18n` +passed in `startos/index.ts`. + ### How long each one may be | | limit | @@ -391,4 +396,4 @@ To support user-managed local folders, attached drives and network shares, decla ## Dependencies -Define dependencies in `startos/dependencies.ts` with `sdk.Dependency.required` or `sdk.Dependency.optional`, and pass the resulting `sdk.Dependencies.of()` builder to `buildManifest(versionGraph, sdkManifest, dependencies)`. See [Dependencies](dependencies.md) for base requirements and runtime narrowing. +Define dependencies in `startos/dependencies.ts` with `sdk.Dependency.required` or `sdk.Dependency.optional`, and pass the resulting `sdk.Dependencies.of()` builder to `buildManifest({ versionGraph, manifest, dependencies, i18n })`. See [Dependencies](dependencies.md) for base requirements and runtime narrowing. diff --git a/projects/start-sdk/docs/src/shared-volumes.md b/projects/start-sdk/docs/src/shared-volumes.md index a17d0bf641..24ef14ae68 100644 --- a/projects/start-sdk/docs/src/shared-volumes.md +++ b/projects/start-sdk/docs/src/shared-volumes.md @@ -6,7 +6,7 @@ Shared volumes are user-owned local folders, folders on attached drives or CIFS/ ## Declare support -Use Start SDK 4.2.0 or later. Add this property to `setupManifest`: +Use Start SDK 5.0.0 or later. Add this property to `setupManifest`: ```ts sharedVolumes: true, diff --git a/projects/start-sdk/lib/i18n/index.ts b/projects/start-sdk/lib/i18n/index.ts index 4367cb9f8a..239e058e61 100644 --- a/projects/start-sdk/lib/i18n/index.ts +++ b/projects/start-sdk/lib/i18n/index.ts @@ -35,7 +35,8 @@ function firstUsableLocale(...candidates: string[]): string | undefined { * @param defaultDict - The default language dictionary mapping strings to numeric indices * @param translations - Translation dictionaries for each supported locale * @param defaultLang - The default language code (e.g., 'en_US') - * @returns A typed i18n function that accepts dictionary keys and optional parameters + * @returns A typed i18n function that accepts dictionary keys and optional parameters, + * carrying the default language as `defaultLang` for `buildManifest` */ export function setupI18n< Dict extends Record, @@ -78,10 +79,7 @@ export function setupI18n< return value } - return function i18n( - key: keyof Dict, - params?: Record, - ): string { + function i18n(key: keyof Dict, params?: Record): string { let result = translation ? translation[defaultDict[key as string]] : (key as string) @@ -94,4 +92,6 @@ export function setupI18n< return result } + + return Object.assign(i18n, { defaultLang }) } diff --git a/projects/start-sdk/lib/manifest/setupManifest.ts b/projects/start-sdk/lib/manifest/setupManifest.ts index c385aa3259..0301093174 100644 --- a/projects/start-sdk/lib/manifest/setupManifest.ts +++ b/projects/start-sdk/lib/manifest/setupManifest.ts @@ -63,8 +63,10 @@ function manifestOsVersion(manifest: SDKManifest): string { * with version graph metadata, OS version, SDK version, and computed fields * (migration ranges, hardware requirements, etc.). * - * @param versions - The service's VersionGraph, used to extract the current version, release notes, and migration ranges - * @param manifest - The SDK manifest definition (from `setupManifest`) + * @param options.versionGraph - The service's VersionGraph, used to extract the current version, release notes, and migration ranges + * @param options.manifest - The SDK manifest definition (from `setupManifest`) + * @param options.dependencies - The service's `Dependencies` builder + * @param options.i18n - The package's own `setupI18n` result; its default language becomes `defaultLocale` * @returns A fully resolved Manifest ready for packaging */ export function buildManifest< @@ -78,11 +80,17 @@ export function buildManifest< images: Record volumes: VolumesTypes[] }, ->( - versions: VersionGraph, - manifest: SDKManifest & Manifest, - dependencies: Dependencies, -): Manifest & T.Manifest { +>({ + versionGraph: versions, + manifest, + dependencies, + i18n, +}: { + versionGraph: VersionGraph + manifest: SDKManifest & Manifest + dependencies: Dependencies + i18n: { readonly defaultLang: string } +}): Manifest & T.Manifest { const images = Object.entries(manifest.images).reduce( (images, [k, v]) => { v.arch = v.arch ?? ['aarch64', 'x86_64', 'riscv64'] @@ -95,6 +103,7 @@ export function buildManifest< ) return { ...manifest, + defaultLocale: i18n.defaultLang, dependencies: dependencies.manifestDependencies(), gitHash: null, osVersion: manifestOsVersion(manifest), diff --git a/projects/start-sdk/lib/test/setupManifest.test.ts b/projects/start-sdk/lib/test/setupManifest.test.ts index 770f963cbf..46a8d5ef31 100644 --- a/projects/start-sdk/lib/test/setupManifest.test.ts +++ b/projects/start-sdk/lib/test/setupManifest.test.ts @@ -2,6 +2,9 @@ import { buildManifest, setupManifest } from '../manifest/setupManifest' import { Dependencies, Dependency } from '../dependencies' import { VersionGraph } from '../version/VersionGraph' import { VersionInfo } from '../version/VersionInfo' +import { setupI18n } from '../i18n' + +const i18n = setupI18n({}, {}, 'en_US') const versions = VersionGraph.of({ current: VersionInfo.of<'1.0.0:0'>({ @@ -41,14 +44,24 @@ function manifest(emulateMissing?: boolean) { } test('defaults to the binding transport enforcement compatibility floor', () => { - expect(buildManifest(versions, manifest(), Dependencies.of()).osVersion).toBe( - '0.4.3', - ) + expect( + buildManifest({ + versionGraph: versions, + manifest: manifest(), + dependencies: Dependencies.of(), + i18n, + }).osVersion, + ).toBe('0.4.3') }) test('pre-download alert is included in the built manifest', () => { expect( - buildManifest(versions, manifest(), Dependencies.of()).preDownloadAlert, + buildManifest({ + versionGraph: versions, + manifest: manifest(), + dependencies: Dependencies.of(), + i18n, + }).preDownloadAlert, ).toEqual({ message: { en_US: 'Back up before updating', @@ -68,7 +81,12 @@ test('the builder publishes its complete base dependency requirements', () => { healthChecks: ['bitcoin-rest'], }), ) - const built = buildManifest(versions, manifest(), dependencies) + const built = buildManifest({ + versionGraph: versions, + manifest: manifest(), + dependencies: dependencies, + i18n, + }) expect(built.dependencies.bitcoind).toEqual({ description: 'Blockchain data', optional: false, @@ -80,14 +98,24 @@ test('the builder publishes its complete base dependency requirements', () => { }) test('images emulate missing architectures by default', () => { - const built = buildManifest(versions, manifest(), Dependencies.of()) + const built = buildManifest({ + versionGraph: versions, + manifest: manifest(), + dependencies: Dependencies.of(), + i18n, + }) expect(built.images.main.emulateMissing).toBe(true) expect(built.hardwareRequirements.arch).toBeNull() }) test('images can require a native architecture', () => { - const built = buildManifest(versions, manifest(false), Dependencies.of()) + const built = buildManifest({ + versionGraph: versions, + manifest: manifest(false), + dependencies: Dependencies.of(), + i18n, + }) expect(built.images.main.emulateMissing).toBe(false) expect(built.hardwareRequirements.arch).toEqual(['aarch64']) @@ -95,10 +123,20 @@ test('images can require a native architecture', () => { test('shared-volume capability defaults to false and preserves explicit opt-in', () => { expect( - buildManifest(versions, manifest(), Dependencies.of()).sharedVolumes, + buildManifest({ + versionGraph: versions, + manifest: manifest(), + dependencies: Dependencies.of(), + i18n, + }).sharedVolumes, ).toBe(false) const optedIn = setupManifest({ ...manifest(), sharedVolumes: true }) - const built = buildManifest(versions, optedIn, Dependencies.of()) + const built = buildManifest({ + versionGraph: versions, + manifest: optedIn, + dependencies: Dependencies.of(), + i18n, + }) expect(built.sharedVolumes).toBe(true) expect(built.osVersion).toBe('0.4.3') }) @@ -106,22 +144,41 @@ test('shared-volume capability defaults to false and preserves explicit opt-in', test('an explicit compatibility override cannot understate shared-volume support', () => { for (const osVersion of ['0.4.2', '0.4.1.1']) { expect(() => - buildManifest( - versions, - setupManifest({ ...manifest(), sharedVolumes: true, osVersion }), - Dependencies.of(), - ), + buildManifest({ + versionGraph: versions, + manifest: setupManifest({ + ...manifest(), + sharedVolumes: true, + osVersion, + }), + dependencies: Dependencies.of(), + i18n, + }), ).toThrow('Shared volumes require StartOS 0.4.3 or later') } expect( - buildManifest( - versions, - setupManifest({ + buildManifest({ + versionGraph: versions, + manifest: setupManifest({ ...manifest(), sharedVolumes: true, osVersion: '0.4.3', }), - Dependencies.of(), - ).osVersion, + dependencies: Dependencies.of(), + i18n, + }).osVersion, ).toBe('0.4.3') }) + +test('the default locale is the given package i18n default language', () => { + const own = setupI18n({}, {}, 'fr_FR') + setupI18n({}, {}, 'de_DE') + expect( + buildManifest({ + versionGraph: versions, + manifest: manifest(), + dependencies: Dependencies.of(), + i18n: own, + }).defaultLocale, + ).toBe('fr_FR') +}) diff --git a/projects/start-sdk/package-lock.json b/projects/start-sdk/package-lock.json index 878aba5d14..27c6ff0650 100644 --- a/projects/start-sdk/package-lock.json +++ b/projects/start-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@start9labs/start-sdk", - "version": "4.2.0", + "version": "5.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@start9labs/start-sdk", - "version": "4.2.0", + "version": "5.0.0", "bundleDependencies": [ "@start9labs/start-core" ], diff --git a/projects/start-sdk/package.json b/projects/start-sdk/package.json index 297119e0b7..d70b381795 100644 --- a/projects/start-sdk/package.json +++ b/projects/start-sdk/package.json @@ -1,6 +1,6 @@ { "name": "@start9labs/start-sdk", - "version": "4.2.0", + "version": "5.0.0", "description": "Software development kit to facilitate packaging services for StartOS", "main": "./lib/index.js", "types": "./lib/index.d.ts", diff --git a/projects/start-sdk/release-notes/5.0.0.md b/projects/start-sdk/release-notes/5.0.0.md new file mode 100644 index 0000000000..6d963c242e --- /dev/null +++ b/projects/start-sdk/release-notes/5.0.0.md @@ -0,0 +1,3 @@ +## Important + +- When upgrading a package to SDK 5.0.0, update `buildManifest` in `startos/index.ts` to take named arguments and the package's `i18n`: add `import { i18n } from './i18n'`, then call `buildManifest({ versionGraph, manifest: sdkManifest, dependencies, i18n })`. The package template already does this. diff --git a/projects/start-wrt/backend/ctrl/src/system.rs b/projects/start-wrt/backend/ctrl/src/system.rs index 1c3b33f236..4bcffa4e0f 100644 --- a/projects/start-wrt/backend/ctrl/src/system.rs +++ b/projects/start-wrt/backend/ctrl/src/system.rs @@ -143,7 +143,7 @@ async fn newer_versions(_ctx: ServerContext) -> Result, Error> }) .map(|(ver, info)| VersionInfo { version: ver, - release_notes: info.release_notes.localized_for("en_US"), + release_notes: info.release_notes.localized_for(Some("en_US"), None), }) .collect(); // Sort ascending by semver precedence. The map above iterates in diff --git a/projects/start-wrt/backend/ctrl/src/update/tests.rs b/projects/start-wrt/backend/ctrl/src/update/tests.rs index 72ffc7c765..bf1fee308e 100644 --- a/projects/start-wrt/backend/ctrl/src/update/tests.rs +++ b/projects/start-wrt/backend/ctrl/src/update/tests.rs @@ -81,7 +81,10 @@ async fn registry_metadata_accepts_current_and_legacy_signature_encodings() { let mut unsigned = asset.clone(); unsigned.signatures.clear(); assert!(unsigned.validate_all(SIG_CONTEXT, None).is_err()); - assert_eq!(info.release_notes.localized_for("en_US"), "Release notes"); + assert_eq!( + info.release_notes.localized_for(Some("en_US"), None), + "Release notes" + ); } } diff --git a/shared-libs/crates/start-core/locales/i18n.yaml b/shared-libs/crates/start-core/locales/i18n.yaml index 12afbb7376..5ef0dca066 100644 --- a/shared-libs/crates/start-core/locales/i18n.yaml +++ b/shared-libs/crates/start-core/locales/i18n.yaml @@ -5631,6 +5631,20 @@ help.arg.cifs-username: fr_FR: "Nom d'utilisateur d'authentification CIFS" pl_PL: "Nazwa użytkownika uwierzytelniania CIFS" +help.arg.registry-default-locale: + en_US: "Locale the registry's own text falls back to, such as en_US" + de_DE: "Gebietsschema, auf das die eigenen Texte des Registrys zurückfallen, z. B. en_US" + es_ES: "Configuración regional a la que recurren los textos propios del registro, como en_US" + fr_FR: "Paramètre régional de repli pour les textes propres au registre, par exemple en_US" + pl_PL: "Ustawienia regionalne, do których wracają własne teksty rejestru, np. en_US" + +help.arg.clear-registry-default-locale: + en_US: "Remove the registry default locale" + de_DE: "Das Standard-Gebietsschema des Registrys entfernen" + es_ES: "Eliminar la configuración regional predeterminada del registro" + fr_FR: "Supprimer le paramètre régional par défaut du registre" + pl_PL: "Usuń domyślne ustawienia regionalne rejestru" + help.arg.clear-registry-description: en_US: "Remove the registry description" de_DE: "Die Registry-Beschreibung entfernen" @@ -8100,6 +8114,13 @@ about.set-registry-description: fr_FR: "Définir la description du registre" pl_PL: "Ustaw opis rejestru" +about.set-registry-default-locale: + en_US: "Set the locale the registry's own text falls back to" + de_DE: "Das Gebietsschema festlegen, auf das die eigenen Texte des Registrys zurückfallen" + es_ES: "Establecer la configuración regional a la que recurren los textos propios del registro" + fr_FR: "Définir le paramètre régional de repli pour les textes propres au registre" + pl_PL: "Ustaw ustawienia regionalne, do których wracają własne teksty rejestru" + about.set-registry-name: en_US: "Set the registry name" de_DE: "Den Registry-Namen festlegen" diff --git a/shared-libs/crates/start-core/mcp-tools.json b/shared-libs/crates/start-core/mcp-tools.json index 86b64ae3c4..9fd256a9f3 100644 --- a/shared-libs/crates/start-core/mcp-tools.json +++ b/shared-libs/crates/start-core/mcp-tools.json @@ -6342,6 +6342,10 @@ "osVersion": { "description": "Client StartOS version. Omission preserves the canonical index format.", "type": ["string", "null"] + }, + "language": { + "description": "Locale to resolve localized text to; one the index lacks gets the fallback. Omission keeps every translation.", + "type": ["string", "null"] } }, "additionalProperties": true @@ -6409,6 +6413,10 @@ "description": { "anyOf": [{ "$ref": "#/$defs/LocaleString" }, { "type": "null" }] }, + "defaultLocale": { + "description": "Locale registry-owned `LocaleString`s fall back to when a requested one is missing.", + "type": ["string", "null"] + }, "package": { "$ref": "#/$defs/PackageIndex" }, "os": { "$ref": "#/$defs/OsIndex" }, "signers": { @@ -6425,6 +6433,7 @@ "name", "icon", "description", + "defaultLocale", "package", "os", "signers", @@ -6704,6 +6713,10 @@ "type": "object", "properties": { "title": { "type": "string" }, + "defaultLocale": { + "description": "Locale this package's `LocaleString`s fall back to when a requested one is missing.", + "type": ["string", "null"] + }, "description": { "$ref": "#/$defs/Description" }, "releaseNotes": { "$ref": "#/$defs/LocaleString" }, "preDownloadAlert": { @@ -7012,6 +7025,10 @@ "description": { "anyOf": [{ "$ref": "#/$defs/LocaleString" }, { "type": "null" }] }, + "defaultLocale": { + "description": "Locale registry-owned `LocaleString`s fall back to when a requested one is missing.", + "type": ["string", "null"] + }, "package": { "$ref": "#/$defs/PackageIndex" }, "os": { "$ref": "#/$defs/OsIndex" }, "signers": { @@ -7025,6 +7042,7 @@ "name", "icon", "description", + "defaultLocale", "package", "os", "signers", @@ -7079,6 +7097,10 @@ "description": "Markdown, shown above the registry's services.", "anyOf": [{ "$ref": "#/$defs/LocaleString" }, { "type": "null" }] }, + "defaultLocale": { + "description": "`FullIndex::default_locale`.", + "type": ["string", "null"] + }, "categories": { "type": "object", "propertyNames": { "type": "string" }, @@ -7095,6 +7117,7 @@ "name", "icon", "description", + "defaultLocale", "categories", "trustSigners" ], @@ -7217,6 +7240,10 @@ "description": "Markdown, shown above the registry's services.", "anyOf": [{ "$ref": "#/$defs/LocaleString" }, { "type": "null" }] }, + "defaultLocale": { + "description": "`FullIndex::default_locale`.", + "type": ["string", "null"] + }, "categories": { "type": "object", "propertyNames": { "type": "string" }, @@ -7229,10 +7256,57 @@ "additionalProperties": { "$ref": "#/$defs/SignerInfo" } } }, - "required": ["name", "icon", "description", "categories", "trustSigners"], + "required": [ + "name", + "icon", + "description", + "defaultLocale", + "categories", + "trustSigners" + ], "additionalProperties": true } }, + { + "name": "registry.info.set-default-locale", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "allOf": [ + { "type": "object", "properties": {}, "additionalProperties": true }, + { "$ref": "#/$defs/RegistryUrlParams" }, + { + "type": "object", + "properties": { + "format": { + "anyOf": [{ "$ref": "#/$defs/IoFormat" }, { "type": "null" }] + } + }, + "additionalProperties": true + }, + { "type": "object", "properties": {}, "additionalProperties": true }, + { "$ref": "#/$defs/SetDefaultLocaleParams" } + ], + "$defs": { + "RegistryUrlParams": { + "type": "object", + "properties": { "registry": { "type": "string" } }, + "required": ["registry"], + "additionalProperties": true + }, + "IoFormat": { + "type": "string", + "enum": ["json", "json-pretty", "yaml", "cbor", "toml", "toml-pretty"] + }, + "SetDefaultLocaleParams": { + "type": "object", + "properties": { "defaultLocale": { "type": ["string", "null"] } }, + "required": ["defaultLocale"], + "additionalProperties": true + } + }, + "type": "object" + } + }, { "name": "registry.info.set-description", "inputSchema": { @@ -9838,6 +9912,10 @@ "type": "object", "properties": { "title": { "type": "string" }, + "defaultLocale": { + "description": "Locale this package's `LocaleString`s fall back to when a requested one is missing.", + "type": ["string", "null"] + }, "description": { "$ref": "#/$defs/Description" }, "releaseNotes": { "$ref": "#/$defs/LocaleString" }, "preDownloadAlert": { diff --git a/shared-libs/crates/start-core/src/bins/mod.rs b/shared-libs/crates/start-core/src/bins/mod.rs index ad70eaa8a3..967f1fa74e 100644 --- a/shared-libs/crates/start-core/src/bins/mod.rs +++ b/shared-libs/crates/start-core/src/bins/mod.rs @@ -51,18 +51,9 @@ pub fn set_locale_from_env() { } pub fn set_locale(lang: &str) { - let mut best = None; - let prefix = lang.split_inclusive("_").next().unwrap(); - for l in rust_i18n::available_locales!() { - if l == lang { - best = Some(l); - break; - } - if best.is_none() && l.starts_with(prefix) { - best = Some(l); - } - } - rust_i18n::set_locale(best.unwrap_or(lang)); + rust_i18n::set_locale( + crate::best_locale(lang, rust_i18n::available_locales!()).unwrap_or(lang), + ); } /// Help text that is not a locale key stays as written. diff --git a/shared-libs/crates/start-core/src/lib.rs b/shared-libs/crates/start-core/src/lib.rs index a9115c06e1..6646a73be7 100644 --- a/shared-libs/crates/start-core/src/lib.rs +++ b/shared-libs/crates/start-core/src/lib.rs @@ -5,6 +5,19 @@ use const_format::formatcp; rust_i18n::i18n!("locales", fallback = ["en_US"]); +/// The candidate serving a language: an exact match, else the first with its language code. +pub fn best_locale<'a>( + lang: &str, + candidates: impl IntoIterator, +) -> Option<&'a str> { + let candidates: Vec<&str> = candidates.into_iter().collect(); + if let Some(exact) = candidates.iter().find(|l| **l == lang) { + return Some(exact); + } + let prefix = lang.split_inclusive('_').next().filter(|p| !p.is_empty())?; + candidates.into_iter().find(|l| l.starts_with(prefix)) +} + pub const DATA_DIR: &str = "/media/startos/data"; pub const MAIN_DATA: &str = formatcp!("{DATA_DIR}/main"); pub const PACKAGE_DATA: &str = formatcp!("{DATA_DIR}/package-data"); diff --git a/shared-libs/crates/start-core/src/registry/context.rs b/shared-libs/crates/start-core/src/registry/context.rs index 11400ce6f7..891ef6e119 100644 --- a/shared-libs/crates/start-core/src/registry/context.rs +++ b/shared-libs/crates/start-core/src/registry/context.rs @@ -32,6 +32,7 @@ use crate::middleware::auth::signature::{ use crate::prelude::*; use crate::registry::RegistryDatabase; use crate::registry::device_info::{DEVICE_INFO_HEADER, DeviceInfo}; +use crate::registry::locales::IndexLocaleTracker; use crate::registry::migrations::run_migrations; use crate::registry::mirror::IndexMirrors; use crate::registry::package::icon::{icons_dir, referenced_icons, sweep_icons}; @@ -111,6 +112,7 @@ pub struct RegistryContextSeed { pub listen: SocketAddr, pub db: TypedPatchDb, pub index_mirrors: IndexMirrors, + pub index_locales: IndexLocaleTracker, pub datadir: PathBuf, pub startwrt: bool, pub rpc_continuations: RpcContinuations, @@ -228,12 +230,14 @@ impl RegistryContext { )) }) .transpose()?; + let index_locales = IndexLocaleTracker::spawn(db.clone()).await?; Ok(Self( Arc::new(RegistryContextSeed { hostnames: config.registry_hostname.clone(), listen: config.registry_listen.unwrap_or(DEFAULT_REGISTRY_LISTEN), db, index_mirrors: IndexMirrors::default(), + index_locales, datadir, startwrt: config.startwrt, rpc_continuations: RpcContinuations::new(), @@ -746,12 +750,14 @@ pub(crate) async fn test_context_for_hosts( }, ); db.put(&ROOT, &database).await.unwrap(); + let index_locales = IndexLocaleTracker::spawn(db.clone()).await.unwrap(); RegistryContext( Arc::new(RegistryContextSeed { hostnames, listen: "127.0.0.1:0".parse().unwrap(), db, index_mirrors: Default::default(), + index_locales, datadir, startwrt: false, rpc_continuations: RpcContinuations::new(), diff --git a/shared-libs/crates/start-core/src/registry/db.rs b/shared-libs/crates/start-core/src/registry/db.rs index 94f8168c65..f7a1bc3228 100644 --- a/shared-libs/crates/start-core/src/registry/db.rs +++ b/shared-libs/crates/start-core/src/registry/db.rs @@ -23,7 +23,7 @@ use crate::prelude::*; use crate::registry::RegistryDatabase; use crate::registry::context::RegistryContext; use crate::registry::device_info::WireCompatibility; -use crate::registry::mirror::{IndexMirror, index_mirror, mirror_key}; +use crate::registry::mirror::{IndexMirror, IndexView, index_mirror, mirror_key}; use crate::registry::package::index::ReaderParams; use crate::registry::upstream::WRITES_INDEX; use crate::rpc_continuations::{Guid, RpcContinuation, WebSocketPolicy}; @@ -147,6 +147,8 @@ pub struct SubscribeIndexParams { pub pointer: Option, /// Client StartOS version. Omission preserves the canonical index format. pub os_version: Option, + /// Locale to resolve localized text to; one the index lacks gets the fallback. Omission keeps every translation. + pub language: Option, #[serde(flatten)] pub reader: ReaderParams, } @@ -158,17 +160,30 @@ async fn visible_subscription( SubscribeIndexParams { pointer, os_version, + language, reader, }: SubscribeIndexParams, ) -> Result<(Arc, Dump, JsonSubscriber), Error> { let pointer = subscription_pointer(pointer)?; - let key = mirror_key(&ctx.db.peek().await, reader.signer)?; let wire = os_version .as_ref() .map(WireCompatibility::for_startos) .transpose()? .unwrap_or_default(); - let mirror = index_mirror(&ctx.index_mirrors, &ctx.db, key, wire, &ctx.datadir).await?; + let (key, view) = match language.as_deref() { + None => ( + mirror_key(&ctx.db.peek().await, reader.signer)?, + IndexView::from(wire), + ), + Some(language) => { + let snapshot = ctx.index_locales.snapshot(ctx.db.sequence().await).await?; + let db: Model = snapshot.source.value.clone().into(); + let key = mirror_key(&db, reader.signer)?; + let view = IndexView::localized(&db, &snapshot.locales, key.as_ref(), wire, language)?; + (key, view) + } + }; + let mirror = index_mirror(&ctx.index_mirrors, &ctx.db, key, view, &ctx.datadir).await?; let (dump, sub) = subscription(&mirror.db, Some(pointer)).await?; Ok((mirror, dump, sub)) } @@ -342,7 +357,11 @@ mod tests { ] { let params: SubscribeIndexParams = serde_json::from_value(params).unwrap(); assert!(params.pointer.is_none()); + assert!(params.language.is_none()); } + let params: SubscribeIndexParams = + serde_json::from_value(serde_json::json!({ "language": "pl_PL" })).unwrap(); + assert_eq!(params.language.as_deref(), Some("pl_PL")); } #[test] diff --git a/shared-libs/crates/start-core/src/registry/device_info.rs b/shared-libs/crates/start-core/src/registry/device_info.rs index 21aeda518b..a8a37ed1c3 100644 --- a/shared-libs/crates/start-core/src/registry/device_info.rs +++ b/shared-libs/crates/start-core/src/registry/device_info.rs @@ -368,7 +368,7 @@ fn project_os_headlines(method: &str, res: &mut Value, legacy: bool) { fn project_legacy_os_notes(method: &str, res: &mut Value) -> Result<(), Error> { for (_, info) in os_version_infos(method, res) { let notes: LocaleString = from_value(info["releaseNotes"].clone())?; - info["releaseNotes"] = Value::String(notes.localized_for("en_US").into()); + info["releaseNotes"] = Value::String(notes.localized_for(Some("en_US"), None).into()); } Ok(()) } diff --git a/shared-libs/crates/start-core/src/registry/info.rs b/shared-libs/crates/start-core/src/registry/info.rs index 379b8964f2..06abb690ec 100644 --- a/shared-libs/crates/start-core/src/registry/info.rs +++ b/shared-libs/crates/start-core/src/registry/info.rs @@ -58,6 +58,15 @@ pub fn info_api() -> ParentHandler> { .no_display() .with_about("about.set-registry-description"), ) + .subcommand( + "set-default-locale", + from_fn_async(set_default_locale) + .with_metadata(WRITES_INDEX, Value::Bool(true)) + .with_metadata("admin", Value::Bool(true)) + .no_display() + .with_about("about.set-registry-default-locale") + .with_call_remote::(), + ) .subcommand( "set-icon", from_fn_async(set_icon) @@ -80,6 +89,9 @@ pub struct RegistryInfo { pub icon: Option>, /// Markdown, shown above the registry's services. pub description: Option, + /// `FullIndex::default_locale`. + #[serde(default)] + pub default_locale: Option, pub categories: BTreeMap, /// Registry-selected signers, not an assertion of trust. #[serde(default)] @@ -100,6 +112,7 @@ pub(crate) fn from_index(index: &Model) -> Result, + #[arg(long, help = "help.arg.clear-registry-default-locale")] + #[serde(skip)] + #[visit(ts(skip))] + pub clear: bool, +} + +rpc_toolkit::reflect_ts!(SetDefaultLocaleParams); +rpc_toolkit::ts_export!(SetDefaultLocaleParams, namespaces = [""]); + +pub async fn set_default_locale( + ctx: RegistryContext, + SetDefaultLocaleParams { default_locale, .. }: SetDefaultLocaleParams, +) -> Result<(), Error> { + ctx.db + .mutate(|db| { + db.as_index_mut() + .as_default_locale_mut() + .ser(&default_locale) + }) + .await + .result +} + #[derive(Debug, Deserialize, Serialize, VisitFields)] #[serde(rename_all = "camelCase")] pub struct SetDescriptionParams { diff --git a/shared-libs/crates/start-core/src/registry/locales.rs b/shared-libs/crates/start-core/src/registry/locales.rs new file mode 100644 index 0000000000..2377d5ca1a --- /dev/null +++ b/shared-libs/crates/start-core/src/registry/locales.rs @@ -0,0 +1,257 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +use patch_db::Dump; +use patch_db::json_ptr::ROOT; +use tokio::sync::watch; + +use crate::PackageId; +use crate::prelude::*; +use crate::registry::package::index::Reader; +use crate::registry::{FullIndex, RegistryDatabase}; +use crate::util::future::NonDetachingJoinHandle; + +/// Locales the index carries translations for, grouped by owning package. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct IndexLocales { + unpackaged: BTreeSet, + packages: BTreeMap>, +} + +impl IndexLocales { + pub fn of(index: &Model) -> Result { + let mut index = index.clone(); + let mut locales = Self::default(); + index.for_each_unpackaged_locale_string(&mut |s| { + locales.unpackaged.extend(s.languages().cloned()) + })?; + for (id, package) in index.as_package_mut().as_packages_mut().as_entries_mut()? { + let mut languages = BTreeSet::new(); + package.for_each_locale_string(&mut |s| languages.extend(s.languages().cloned()))?; + locales.packages.insert(id, languages); + } + Ok(locales) + } + + /// Locales outside packages, plus those of packages visible to the reader. + pub fn visible_to( + &self, + db: &Model, + reader: Option<&Reader>, + ) -> Result, Error> { + let packages = db.as_index().as_package(); + let mut visible: BTreeSet<&str> = self.unpackaged.iter().map(|l| &**l).collect(); + for (id, languages) in &self.packages { + if packages.visible_package(id, reader)?.is_some() { + visible.extend(languages.iter().map(|l| &**l)); + } + } + Ok(visible) + } +} + +/// Database and locale metadata from one revision. +pub struct IndexLocaleSnapshot { + pub source: Dump, + pub locales: IndexLocales, +} + +/// Subscription snapshots pair locale metadata with the same source revision. +pub struct IndexLocaleTracker { + locales: watch::Receiver, Arc>>, + _task: NonDetachingJoinHandle<()>, +} + +impl IndexLocaleTracker { + pub async fn spawn(db: TypedPatchDb) -> Result { + let (source, mut sub) = db.dump_and_sub(ROOT.to_owned()).await; + let database: Model = source.value.clone().into(); + let mut snapshot = Arc::new(IndexLocaleSnapshot { + locales: IndexLocales::of(database.as_index())?, + source, + }); + let (send, locales) = watch::channel(Ok(snapshot.clone())); + let task = tokio::spawn(async move { + while sub.recv().await.is_some() { + while sub.try_recv().is_ok() {} + let source = db.dump(&ROOT).await; + let next = if source.value["index"] == snapshot.source.value["index"] { + Ok(snapshot.locales.clone()) + } else { + let database: Model = source.value.clone().into(); + IndexLocales::of(database.as_index()) + }; + match next { + Ok(locales) => { + snapshot = Arc::new(IndexLocaleSnapshot { source, locales }); + send.send_modify(|current| *current = Ok(snapshot.clone())); + } + Err(e) => { + tracing::error!("Error tracking registry index locales: {e}"); + tracing::debug!("{e:?}"); + send.send_modify(|current| *current = Err(Arc::new(e))); + break; + } + } + } + }); + Ok(Self { + locales, + _task: task.into(), + }) + } + + /// Returns matching database and locale snapshots at or after the requested revision. + pub async fn snapshot(&self, sequence: u64) -> Result, Error> { + let mut locales = self.locales.clone(); + let snapshot = locales + .wait_for(|snapshot| match snapshot { + Ok(snapshot) => snapshot.source.id >= sequence, + Err(_) => true, + }) + .await + .with_kind(ErrorKind::Database)?; + match &*snapshot { + Ok(snapshot) => Ok(snapshot.clone()), + Err(error) => Err(error.clone_output()), + } + } +} + +#[cfg(test)] +mod tests { + use std::path::Path; + use std::time::Duration; + + use imbl_value::json; + use patch_db::PatchDb; + use patch_db::json_ptr::JsonPointer; + + use super::*; + use crate::registry::device_info::WireCompatibility; + use crate::registry::mirror::{IndexMirrors, IndexView, index_mirror}; + + fn version(notes: Value) -> Value { + json!({ + "title": "Package", + "description": { "short": "Short", "long": "Long" }, + "releaseNotes": notes, + "dependencyMetadata": {}, + }) + } + + #[tokio::test] + async fn tracker_follows_index_revisions() { + let db = TypedPatchDb::::load_unchecked(PatchDb::in_memory()); + db.put( + &JsonPointer::<&str>::default(), + &json!({ + "admins": [], + "index": { + "description": { "en_US": "Registry", "pl_PL": "Rejestr" }, + "package": { "categories": {}, "packages": {} }, + "os": { "versions": {} }, + }, + }), + ) + .await + .unwrap(); + let tracker = IndexLocaleTracker::spawn(db.clone()).await.unwrap(); + let languages = |snapshot: &IndexLocaleSnapshot| { + let mut all = snapshot.locales.unpackaged.clone(); + all.extend(snapshot.locales.packages.values().flatten().cloned()); + all.into_iter().map(|l| l.to_string()).collect::>() + }; + let initial = tracker.snapshot(db.sequence().await).await.unwrap(); + assert_eq!(languages(&initial), ["en_US", "pl_PL"]); + + db.put( + &"/index/package/packages/pkg" + .parse::() + .unwrap(), + &json!({ + "authorized": {}, + "categories": [], + "versions": { + "1.0.0:0": version(json!({ "en_US": "Notes", "ja_JP": "ノート" })), + }, + }), + ) + .await + .unwrap(); + let added = tokio::time::timeout( + Duration::from_secs(5), + tracker.snapshot(db.sequence().await), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(languages(&added), ["en_US", "ja_JP", "pl_PL"]); + assert_eq!( + added.locales.packages[&"pkg".parse::().unwrap()] + .iter() + .map(|l| &**l) + .collect::>(), + ["en_US", "ja_JP"] + ); + let database: Model = added.source.value.clone().into(); + let view = IndexView::localized( + &database, + &added.locales, + None, + WireCompatibility::default(), + "ja_JP", + ) + .unwrap(); + let mirror = index_mirror(&IndexMirrors::default(), &db, None, view, Path::new("")) + .await + .unwrap(); + assert_eq!( + mirror + .db + .dump( + &"/index/package/packages/pkg/versions/1.0.0:0/releaseNotes" + .parse::() + .unwrap(), + ) + .await + .value, + json!("ノート") + ); + + let admins = json!([crate::rpc_continuations::Guid::new()]); + db.put(&"/admins".parse::().unwrap(), &admins) + .await + .unwrap(); + let permissions = tokio::time::timeout( + Duration::from_secs(5), + tracker.snapshot(db.sequence().await), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(permissions.source.value["admins"], admins); + assert_eq!(languages(&permissions), ["en_US", "ja_JP", "pl_PL"]); + + db.put( + &"/index/package/packages".parse::().unwrap(), + &json!({}), + ) + .await + .unwrap(); + let removed = tokio::time::timeout( + Duration::from_secs(5), + tracker.snapshot(db.sequence().await), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(languages(&removed), ["en_US", "pl_PL"]); + assert!( + removed.source.value["index"]["package"]["packages"] + .as_object() + .unwrap() + .is_empty() + ); + } +} diff --git a/shared-libs/crates/start-core/src/registry/mirror.rs b/shared-libs/crates/start-core/src/registry/mirror.rs index b10d742aa2..d01b76b834 100644 --- a/shared-libs/crates/start-core/src/registry/mirror.rs +++ b/shared-libs/crates/start-core/src/registry/mirror.rs @@ -7,15 +7,63 @@ use patch_db::{ModelExt, PatchDb}; use tokio::sync::watch; use crate::prelude::*; -use crate::registry::RegistryDatabase; use crate::registry::device_info::WireCompatibility; +use crate::registry::locales::IndexLocales; use crate::registry::package::icon::icons_dir; use crate::registry::package::index::Reader; +use crate::registry::{FullIndex, RegistryDatabase}; use crate::sign::AnyVerifyingKey; use crate::util::future::NonDetachingJoinHandle; pub type IndexMirrors = - tokio::sync::Mutex, WireCompatibility), Weak>>; + tokio::sync::Mutex, IndexView), Weak>>; + +/// Client-specific presentation of the index; equal views share one mirror. +#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub struct IndexView { + pub wire: WireCompatibility, + /// Unset keeps every translation. + language: Option, +} + +/// Translation each `LocaleString` in a view resolves to. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum ViewLanguage { + Locale(InternedString), + /// Each owner's declared default, for a language matching none in the index. + Default, +} + +impl IndexView { + /// A language matching none of the reader's visible locales shares the default view. + pub fn localized( + db: &Model, + locales: &IndexLocales, + key: Option<&AnyVerifyingKey>, + wire: WireCompatibility, + language: &str, + ) -> Result { + let reader = Reader::resolve(db, key)?; + let visible = locales.visible_to(db, reader.as_ref())?; + let language = match crate::best_locale(language, visible) { + Some(locale) => ViewLanguage::Locale(InternedString::intern(locale)), + None => ViewLanguage::Default, + }; + Ok(Self { + wire, + language: Some(language), + }) + } +} + +impl From for IndexView { + fn from(wire: WireCompatibility) -> Self { + Self { + wire, + language: None, + } + } +} pub struct IndexMirror { pub db: PatchDb, @@ -27,13 +75,13 @@ impl IndexMirror { async fn spawn( main: &TypedPatchDb, key: Option, - wire: WireCompatibility, + view: IndexView, datadir: &Path, ) -> Result, Error> { let (dump, mut sub) = main.dump_and_sub(JsonPointer::default()).await; let mut root = dump.value; let icons = icons_dir(datadir); - let visible = projected_root(&root, key.as_ref(), wire, &icons).await?; + let visible = projected_root(&root, key.as_ref(), &view, &icons).await?; let db = PatchDb::in_memory(); db.put(&JsonPointer::<&str>::default(), &visible).await?; let mirror = db.clone(); @@ -43,7 +91,7 @@ impl IndexMirror { let res = async { patch_db::json_patch::patch(&mut root, &rev.patch) .map_err(|e| Error::new(eyre!("{e}"), ErrorKind::Database))?; - let next = projected_root(&root, key.as_ref(), wire, &icons).await?; + let next = projected_root(&root, key.as_ref(), &view, &icons).await?; mirror.put(&JsonPointer::<&str>::default(), &next).await?; Ok::<_, Error>(()) } @@ -96,10 +144,10 @@ pub async fn index_mirror( mirrors: &IndexMirrors, main: &TypedPatchDb, key: Option, - wire: WireCompatibility, + view: IndexView, datadir: &Path, ) -> Result, Error> { - let identity = (key.as_ref().map(|key| key.interned_der64()), wire); + let identity = (key.as_ref().map(|key| key.interned_der64()), view.clone()); let mut mirrors = mirrors.lock().await; if let Some(mirror) = mirrors .get(&identity) @@ -108,7 +156,7 @@ pub async fn index_mirror( { return Ok(mirror); } - let mirror = IndexMirror::spawn(main, key, wire, datadir).await?; + let mirror = IndexMirror::spawn(main, key, view, datadir).await?; mirrors.retain(|_, m| m.strong_count() > 0); mirrors.insert(identity, Arc::downgrade(&mirror)); Ok(mirror) @@ -117,21 +165,30 @@ pub async fn index_mirror( async fn projected_root( root: &Value, key: Option<&AnyVerifyingKey>, - wire: WireCompatibility, + view: &IndexView, icons: &Path, ) -> Result { - let mut visible = visible_root(root, key)?; - wire.project(icons, "index", &Value::Null, &mut visible["index"]) + let mut index = visible_index(root.clone().into(), key)?; + match &view.language { + Some(ViewLanguage::Locale(locale)) => index.localize_for(Some(locale))?, + Some(ViewLanguage::Default) => index.localize_for(None)?, + None => (), + } + let mut visible = imbl_value::json!({ "index": index.into_value() }); + view.wire + .project(icons, "index", &Value::Null, &mut visible["index"]) .await?; Ok(visible) } -fn visible_root(root: &Value, key: Option<&AnyVerifyingKey>) -> Result { - let db: Model = root.clone().into(); +fn visible_index( + db: Model, + key: Option<&AnyVerifyingKey>, +) -> Result, Error> { let reader = Reader::resolve(&db, key)?; let mut index = db.into_index(); index.as_package_mut().retain_visible(reader.as_ref())?; - Ok(imbl_value::json!({ "index": index.into_value() })) + Ok(index) } #[cfg(test)] @@ -190,34 +247,32 @@ mod tests { .collect() } - #[test] - fn visible_root_hides_private_packages_from_everyone_else() { + async fn visible_root(root: &Value, key: Option<&AnyVerifyingKey>) -> Value { + projected_root(root, key, &IndexView::default(), Path::new("")) + .await + .unwrap() + } + + #[tokio::test] + async fn visible_root_hides_private_packages_from_everyone_else() { let reader = Guid::new(); let private = root(true, &reader, &[]); - let visible = visible_root(&private, None).unwrap(); + let visible = visible_root(&private, None).await; assert_eq!(packages(&visible), ["public"]); assert!(visible.get("admins").is_none()); + let stranger = + crate::sign::AnySigningKey::Ed25519(ed25519_dalek::SigningKey::from_bytes(&[8; 32])) + .verifying_key(); assert_eq!( - packages( - &visible_root( - &private, - Some( - &crate::sign::AnySigningKey::Ed25519( - ed25519_dalek::SigningKey::from_bytes(&[8; 32]) - ) - .verifying_key() - ) - ) - .unwrap() - ), + packages(&visible_root(&private, Some(&stranger)).await), ["public"] ); assert_eq!( - packages(&visible_root(&private, Some(&key())).unwrap()), + packages(&visible_root(&private, Some(&key())).await), ["public", "secret"] ); assert_eq!( - packages(&visible_root(&root(false, &reader, &[]), None).unwrap()), + packages(&visible_root(&root(false, &reader, &[]), None).await), ["public", "secret"] ); } @@ -266,7 +321,7 @@ mod tests { &mirrors, &main, Some(key()), - WireCompatibility::default(), + IndexView::default(), Path::new(""), ) .await @@ -306,30 +361,18 @@ mod tests { .await .unwrap(); let mirrors = IndexMirrors::default(); - let public = index_mirror( - &mirrors, - &main, - None, - WireCompatibility::default(), - Path::new(""), - ) - .await - .unwrap(); - let shared = index_mirror( - &mirrors, - &main, - None, - WireCompatibility::default(), - Path::new(""), - ) - .await - .unwrap(); + let public = index_mirror(&mirrors, &main, None, IndexView::default(), Path::new("")) + .await + .unwrap(); + let shared = index_mirror(&mirrors, &main, None, IndexView::default(), Path::new("")) + .await + .unwrap(); assert!(Arc::ptr_eq(&public, &shared)); let own = index_mirror( &mirrors, &main, Some(key()), - WireCompatibility::default(), + IndexView::default(), Path::new(""), ) .await @@ -361,15 +404,9 @@ mod tests { ); drop((public, shared)); - let fresh = index_mirror( - &mirrors, - &main, - None, - WireCompatibility::default(), - Path::new(""), - ) - .await - .unwrap(); + let fresh = index_mirror(&mirrors, &main, None, IndexView::default(), Path::new("")) + .await + .unwrap(); assert_eq!(mirrors.lock().await.len(), 2); drop(fresh); } diff --git a/shared-libs/crates/start-core/src/registry/mirror/tests/compatibility.rs b/shared-libs/crates/start-core/src/registry/mirror/tests/compatibility.rs index 48748d4f7f..c0f216212f 100644 --- a/shared-libs/crates/start-core/src/registry/mirror/tests/compatibility.rs +++ b/shared-libs/crates/start-core/src/registry/mirror/tests/compatibility.rs @@ -1,4 +1,5 @@ use super::*; +use crate::registry::locales::IndexLocales; use crate::registry::package::icon::store_icon; use crate::sign::AnySignature; @@ -56,7 +57,7 @@ async fn equivalent_versions_share_replicas_and_versioned_privacy_survives_revis &mirrors, &fixture.main, None, - wire("0.4.0.2"), + wire("0.4.0.2").into(), fixture.dir.path(), ) .await @@ -65,7 +66,7 @@ async fn equivalent_versions_share_replicas_and_versioned_privacy_survives_revis &mirrors, &fixture.main, None, - wire("0.4.0.1"), + wire("0.4.0.1").into(), fixture.dir.path(), ) .await @@ -75,7 +76,7 @@ async fn equivalent_versions_share_replicas_and_versioned_privacy_survives_revis &mirrors, &fixture.main, None, - wire("0.4.3.1"), + wire("0.4.3.1").into(), fixture.dir.path(), ) .await @@ -84,7 +85,7 @@ async fn equivalent_versions_share_replicas_and_versioned_privacy_survives_revis &mirrors, &fixture.main, None, - WireCompatibility::default(), + IndexView::default(), fixture.dir.path(), ) .await @@ -95,7 +96,7 @@ async fn equivalent_versions_share_replicas_and_versioned_privacy_survives_revis &mirrors, &fixture.main, None, - wire("0.4.3"), + wire("0.4.3").into(), fixture.dir.path(), ) .await @@ -105,7 +106,7 @@ async fn equivalent_versions_share_replicas_and_versioned_privacy_survives_revis &mirrors, &fixture.main, None, - wire("0.4.1.3"), + wire("0.4.1.3").into(), fixture.dir.path(), ) .await @@ -115,7 +116,7 @@ async fn equivalent_versions_share_replicas_and_versioned_privacy_survives_revis &mirrors, &fixture.main, Some(key()), - wire("0.4.0.2"), + wire("0.4.0.2").into(), fixture.dir.path(), ) .await @@ -125,7 +126,7 @@ async fn equivalent_versions_share_replicas_and_versioned_privacy_survives_revis &mirrors, &fixture.main, None, - wire("0.4.0.4"), + wire("0.4.0.4").into(), fixture.dir.path(), ) .await @@ -264,7 +265,7 @@ async fn inaccessible_private_icons_are_not_loaded_by_legacy_replicas() { &IndexMirrors::default(), &fixture.main, None, - wire("0.4.0.2"), + wire("0.4.0.2").into(), fixture.dir.path(), ) .await @@ -283,7 +284,7 @@ async fn collected_icon_in_an_older_revision_terminates_and_rebuilds_the_replica &mirrors, &fixture.main, None, - wire("0.4.0.2"), + wire("0.4.0.2").into(), fixture.dir.path(), ) .await @@ -292,7 +293,7 @@ async fn collected_icon_in_an_older_revision_terminates_and_rebuilds_the_replica &mirrors, &fixture.main, None, - WireCompatibility::default(), + IndexView::default(), fixture.dir.path(), ) .await @@ -325,7 +326,7 @@ async fn collected_icon_in_an_older_revision_terminates_and_rebuilds_the_replica &mirrors, &fixture.main, None, - wire("0.4.0.2"), + wire("0.4.0.2").into(), fixture.dir.path(), ) .await @@ -338,3 +339,171 @@ async fn collected_icon_in_an_older_revision_terminates_and_rebuilds_the_replica json!("data:image/png;base64,bmV4dA==") ); } + +fn translated(en: &str, pl: &str) -> Value { + json!({ "en_US": en, "pl_PL": pl }) +} + +#[tokio::test] +async fn language_views_share_replicas_and_localize_snapshots_and_revisions() { + let fixture = fixture().await; + let mut state = fixture.main.peek().await.into_value(); + state["index"]["description"] = translated("Registry", "Rejestr"); + state["index"]["defaultLocale"] = json!("pl_PL"); + state["index"]["package"]["categories"] = + json!({ "tools": { "name": translated("Tools", "Narzędzia") } }); + let public = &mut state["index"]["package"]["packages"]["public"]["versions"]["1.0.0:0"]; + public["description"] = json!({ "short": translated("Short", "Krótki"), "long": "Long" }); + public["releaseNotes"] = translated("Notes", "Notatki"); + public["defaultLocale"] = json!("en_US"); + public["preDownloadAlert"] = json!({ + "message": translated("Back up", "Zrób kopię"), + "when": { "sourceVersion": "*" }, + }); + public["dependencyMetadata"]["dep"]["title"] = translated("Dependency", "Zależność"); + public["dependencyMetadata"]["dep"]["description"] = json!(null); + public["dependencyMetadata"]["dep"]["optional"] = json!(false); + let secret = &mut state["index"]["package"]["packages"]["secret"]["versions"]["1.0.0:0"]; + secret["description"] = json!({ "short": "Short", "long": "Long" }); + secret["releaseNotes"] = json!({ "en_US": "Notes", "ja_JP": "ノート" }); + secret["dependencyMetadata"]["dep"]["title"] = json!(null); + secret["dependencyMetadata"]["dep"]["description"] = json!(null); + secret["dependencyMetadata"]["dep"]["optional"] = json!(false); + fixture + .main + .put(&JsonPointer::<&str>::default(), &state) + .await + .unwrap(); + + let snapshot = fixture.main.peek().await; + let locales = IndexLocales::of(snapshot.as_index()).unwrap(); + let mirrors = IndexMirrors::default(); + let reader_mirror = + |key: Option, wire: WireCompatibility, language: Option<&str>| { + let view = match language { + Some(language) => { + IndexView::localized(&snapshot, &locales, key.as_ref(), wire, language).unwrap() + } + None => IndexView::from(wire), + }; + index_mirror(&mirrors, &fixture.main, key, view, fixture.dir.path()) + }; + let mirror = + |wire: WireCompatibility, language: Option<&str>| reader_mirror(None, wire, language); + let current = WireCompatibility::default(); + let polish = mirror(current, Some("pl_PL")).await.unwrap(); + for related in ["pl_PL", "pl", "pl_XX"] { + assert!(Arc::ptr_eq( + &polish, + &mirror(current, Some(related)).await.unwrap() + )); + } + let canonical = mirror(current, None).await.unwrap(); + let english = mirror(current, Some("en_US")).await.unwrap(); + assert!(Arc::ptr_eq( + &english, + &mirror(current, Some("en_GB")).await.unwrap() + )); + let default_view = mirror(current, Some("zz_ZZ")).await.unwrap(); + assert!(!Arc::ptr_eq(&english, &default_view)); + for absent in ["", "de_DE", "ja_JP"] { + assert!(Arc::ptr_eq( + &default_view, + &mirror(current, Some(absent)).await.unwrap() + )); + } + let japanese = reader_mirror(Some(key()), current, Some("ja_JP")) + .await + .unwrap(); + let reader_english = reader_mirror(Some(key()), current, Some("en_US")) + .await + .unwrap(); + assert!(!Arc::ptr_eq(&japanese, &reader_english)); + assert_eq!( + japanese.db.dump(&"/index".parse().unwrap()).await.value["package"]["packages"]["secret"]["versions"] + ["1.0.0:0"]["releaseNotes"], + json!("ノート") + ); + drop((japanese, reader_english)); + let legacy_polish = mirror(wire("0.4.0.2"), Some("pl_PL")).await.unwrap(); + for other in [&canonical, &english, &default_view, &legacy_polish] { + assert!(!Arc::ptr_eq(&polish, other)); + } + assert_eq!(mirrors.lock().await.len(), 5); + + let pointer: JsonPointer = "/index".parse().unwrap(); + let (dump, mut sub) = polish.db.dump_and_sub(pointer.clone()).await; + let mut polish_view = dump.value; + assert_eq!(polish_view["description"], json!("Rejestr")); + assert_eq!( + polish_view["package"]["categories"]["tools"]["name"], + json!("Narzędzia") + ); + let version = &polish_view["package"]["packages"]["public"]["versions"]["1.0.0:0"]; + assert_eq!(version["description"]["short"], json!("Krótki")); + assert_eq!(version["description"]["long"], json!("Long")); + assert_eq!(version["releaseNotes"], json!("Notatki")); + assert_eq!(version["preDownloadAlert"]["message"], json!("Zrób kopię")); + assert_eq!( + version["dependencyMetadata"]["dep"]["title"], + json!("Zależność") + ); + assert_eq!( + polish_view["os"]["versions"]["0.4.0.6"]["releaseNotes"], + json!("Polski") + ); + let english_view = english.db.dump(&pointer).await.value; + assert_eq!(english_view["description"], json!("Registry")); + assert_eq!( + english_view["os"]["versions"]["0.4.0.6"]["releaseNotes"], + json!("English") + ); + assert_eq!( + english_view["package"]["packages"]["public"]["versions"]["1.0.0:0"]["releaseNotes"], + json!("Notes") + ); + let default_view = default_view.db.dump(&pointer).await.value; + assert_eq!(default_view["description"], json!("Rejestr")); + assert_eq!( + default_view["package"]["categories"]["tools"]["name"], + json!("Narzędzia") + ); + assert_eq!( + default_view["package"]["packages"]["public"]["versions"]["1.0.0:0"]["releaseNotes"], + json!("Notes") + ); + let legacy_view = legacy_polish.db.dump(&pointer).await.value; + assert_eq!( + legacy_view["os"]["versions"]["0.4.0.6"]["releaseNotes"], + json!("Polski") + ); + assert_eq!( + legacy_view["package"]["packages"]["public"]["versions"]["1.0.0:0"]["icon"], + json!("data:image/png;base64,cHVibGlj") + ); + let canonical_view = canonical.db.dump(&pointer).await.value; + assert_eq!( + canonical_view["description"], + translated("Registry", "Rejestr") + ); + + state["index"]["os"]["versions"]["0.4.0.6"]["releaseNotes"] = translated("Updated", "Nowe"); + fixture + .main + .put(&JsonPointer::<&str>::default(), &state) + .await + .unwrap(); + let revision = tokio::time::timeout(std::time::Duration::from_secs(5), sub.recv()) + .await + .unwrap() + .unwrap(); + patch_db::json_patch::patch(&mut polish_view, &revision.patch).unwrap(); + assert_eq!( + polish_view["os"]["versions"]["0.4.0.6"]["releaseNotes"], + json!("Nowe") + ); + assert_eq!( + fixture.main.peek().await.into_value()["index"]["description"], + translated("Registry", "Rejestr") + ); +} diff --git a/shared-libs/crates/start-core/src/registry/mod.rs b/shared-libs/crates/start-core/src/registry/mod.rs index fba8764b1d..1064af6a0d 100644 --- a/shared-libs/crates/start-core/src/registry/mod.rs +++ b/shared-libs/crates/start-core/src/registry/mod.rs @@ -34,6 +34,7 @@ pub mod context; pub mod db; pub mod device_info; pub mod info; +pub mod locales; pub mod metrics; mod migrations; pub mod mirror; @@ -77,6 +78,9 @@ pub struct FullIndex { pub name: Option, pub icon: Option>, pub description: Option, + /// Locale registry-owned `LocaleString`s fall back to when a requested one is missing. + #[serde(default)] + pub default_locale: Option, pub package: PackageIndex, pub os: OsIndex, pub signers: BTreeMap, @@ -95,6 +99,36 @@ impl Model { Ok(()) }) } + + /// Resolves every `LocaleString` with `LocaleString::localize_for` and its owner's default. + pub fn localize_for(&mut self, locale: Option<&str>) -> Result<(), Error> { + let default = self.as_default_locale().de()?; + self.for_each_unpackaged_locale_string(&mut |s| { + s.localize_for(locale, default.as_deref()) + })?; + for (_, package) in self.as_package_mut().as_packages_mut().as_entries_mut()? { + for (_, version) in package.as_versions_mut().as_entries_mut()? { + version.localize_for(locale)?; + } + } + Ok(()) + } + + /// Visits every `LocaleString` outside `PackageIndex.packages`. + pub(crate) fn for_each_unpackaged_locale_string( + &mut self, + f: &mut impl FnMut(&mut LocaleString), + ) -> Result<(), Error> { + self.as_description_mut() + .mutate(|d| Ok(d.iter_mut().for_each(&mut *f)))?; + for (_, category) in self.as_package_mut().as_categories_mut().as_entries_mut()? { + category.as_name_mut().mutate(|n| Ok(f(n)))?; + } + for (_, version) in self.as_os_mut().as_versions_mut().as_entries_mut()? { + version.as_release_notes_mut().mutate(|n| Ok(f(n)))?; + } + Ok(()) + } } pub async fn get_full_index( diff --git a/shared-libs/crates/start-core/src/registry/os/ingestion_tests.rs b/shared-libs/crates/start-core/src/registry/os/ingestion_tests.rs index cd72855e5c..31e384d4b6 100644 --- a/shared-libs/crates/start-core/src/registry/os/ingestion_tests.rs +++ b/shared-libs/crates/start-core/src/registry/os/ingestion_tests.rs @@ -414,7 +414,7 @@ async fn os_version_edits_preserve_omitted_metadata_assets_and_signers() { &ctx.index_mirrors, &ctx.db, None, - wire, + wire.into(), &ctx.datadir, ) .await diff --git a/shared-libs/crates/start-core/src/registry/os/version/mod.rs b/shared-libs/crates/start-core/src/registry/os/version/mod.rs index 6c214e306d..d3fe359c6e 100644 --- a/shared-libs/crates/start-core/src/registry/os/version/mod.rs +++ b/shared-libs/crates/start-core/src/registry/os/version/mod.rs @@ -356,7 +356,7 @@ pub fn display_version_info(params: WithIoFormat, info: Value) -> Result<( for (version, info) in &info { table.add_row(row![ &version.to_string(), - &info.release_notes.clone().localized(), + &info.release_notes.clone().localized(None), info.git_hash.as_deref().unwrap_or("N/A"), info.security, &info.iso.keys().into_iter().join(", "), diff --git a/shared-libs/crates/start-core/src/registry/package/category.rs b/shared-libs/crates/start-core/src/registry/package/category.rs index 3e8ff0c83b..da58d2ebc5 100644 --- a/shared-libs/crates/start-core/src/registry/package/category.rs +++ b/shared-libs/crates/start-core/src/registry/package/category.rs @@ -210,7 +210,7 @@ pub fn display_categories( "NAME", ]); for (id, info) in categories { - table.add_row(row![&*id, &info.name.localized()]); + table.add_row(row![&*id, &info.name.localized(None)]); } print_table(&table)?; Ok(()) diff --git a/shared-libs/crates/start-core/src/registry/package/get.rs b/shared-libs/crates/start-core/src/registry/package/get.rs index 75e67bc909..d9c29f5c18 100644 --- a/shared-libs/crates/start-core/src/registry/package/get.rs +++ b/shared-libs/crates/start-core/src/registry/package/get.rs @@ -57,6 +57,9 @@ impl Default for PackageDetailLevel { #[serde(rename_all = "camelCase")] pub struct PackageInfoShort { pub release_notes: LocaleString, + /// `PackageMetadata::default_locale`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_locale: Option, } rpc_toolkit::reflect_ts!(PackageInfoShort); @@ -126,7 +129,7 @@ impl GetPackageResponse { for (version, info) in lesser_versions { table.add_row(row![ AsRef::::as_ref(&version), - &info.release_notes.localized() + &info.release_notes.localized(info.default_locale.as_deref()) ]); } } @@ -876,6 +879,7 @@ fn check_matching_info_short() { let info = PackageVersionInfo { metadata: PackageMetadata { title: "Test Package".into(), + default_locale: None, description: Description { short: lang_map("A short description"), long: lang_map("A longer description of the test package"), diff --git a/shared-libs/crates/start-core/src/registry/package/index.rs b/shared-libs/crates/start-core/src/registry/package/index.rs index 43557a5eed..2581bcde6e 100644 --- a/shared-libs/crates/start-core/src/registry/package/index.rs +++ b/shared-libs/crates/start-core/src/registry/package/index.rs @@ -116,6 +116,18 @@ impl Model { } } +impl Model { + pub(crate) fn for_each_locale_string( + &mut self, + f: &mut impl FnMut(&mut LocaleString), + ) -> Result<(), Error> { + for (_, version) in self.as_versions_mut().as_entries_mut()? { + version.for_each_locale_string(f)?; + } + Ok(()) + } +} + impl Model { pub fn visible_package( &self, @@ -203,13 +215,6 @@ pub struct DependencyMetadata { rpc_toolkit::reflect_ts!(DependencyMetadata); rpc_toolkit::ts_export!(DependencyMetadata, namespaces = [""]); -impl DependencyMetadata { - pub fn localize_for(&mut self, locale: &str) { - self.title.as_mut().map(|t| t.localize_for(locale)); - self.description.as_mut().map(|d| d.localize_for(locale)); - } -} - fn placeholder_url() -> Url { "https://example.com".parse().unwrap() } @@ -238,6 +243,9 @@ rpc_toolkit::ts_export!(PreDownloadAlert, namespaces = [""]); #[model = "Model"] pub struct PackageMetadata { pub title: InternedString, + /// Locale this package's `LocaleString`s fall back to when a requested one is missing. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_locale: Option, pub description: Description, pub release_notes: LocaleString, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -393,13 +401,13 @@ impl PackageVersionInfo { table.add_row(row![bc => &self.metadata.title]); table.add_row(row![br -> "VERSION", AsRef::::as_ref(version)]); - table.add_row(row![br -> "RELEASE NOTES", &self.metadata.release_notes.localized()]); + table.add_row(row![br -> "RELEASE NOTES", &self.metadata.release_notes.localized(self.metadata.default_locale.as_deref())]); table.add_row( - row![br -> "ABOUT", &textwrap::wrap(&self.metadata.description.short.localized(), 80).join("\n")], + row![br -> "ABOUT", &textwrap::wrap(&self.metadata.description.short.localized(self.metadata.default_locale.as_deref()), 80).join("\n")], ); table.add_row(row![ br -> "DESCRIPTION", - &textwrap::wrap(&self.metadata.description.long.localized(), 80).join("\n") + &textwrap::wrap(&self.metadata.description.long.localized(self.metadata.default_locale.as_deref()), 80).join("\n") ]); table.add_row(row![br -> "GIT HASH", self.metadata.git_hash.as_deref().unwrap_or("N/A")]); table.add_row(row![br -> "LICENSE", &self.metadata.license]); @@ -445,29 +453,46 @@ impl Model { } if let Some(locale) = device_info.os.language.as_deref() { - self.as_dependency_metadata_mut() - .as_entries_mut()? - .into_iter() - .try_for_each(|(_, d)| d.mutate(|d| Ok(d.localize_for(locale))))?; - self.as_metadata_mut() - .as_description_mut() - .mutate(|d| Ok(d.localize_for(locale)))?; - self.as_metadata_mut() - .as_release_notes_mut() - .mutate(|r| Ok(r.localize_for(locale)))?; - self.as_metadata_mut() - .as_pre_download_alert_mut() - .mutate(|alert| { - if let Some(alert) = alert { - alert.message.localize_for(locale); - } - Ok(()) - })?; + self.localize_for(Some(locale))?; } } Ok(true) } + + /// Resolves every `LocaleString` with `LocaleString::localize_for` and the declared default. + pub fn localize_for(&mut self, locale: Option<&str>) -> Result<(), Error> { + let default = self.as_metadata().as_default_locale().de()?; + self.for_each_locale_string(&mut |s| s.localize_for(locale, default.as_deref())) + } + + pub(crate) fn for_each_locale_string( + &mut self, + f: &mut impl FnMut(&mut LocaleString), + ) -> Result<(), Error> { + for (_, dependency) in self.as_dependency_metadata_mut().as_entries_mut()? { + dependency.mutate(|d| { + d.title + .iter_mut() + .chain(&mut d.description) + .for_each(&mut *f); + Ok(()) + })?; + } + let metadata = self.as_metadata_mut(); + metadata.as_description_mut().mutate(|d| { + f(&mut d.short); + f(&mut d.long); + Ok(()) + })?; + metadata.as_release_notes_mut().mutate(|r| Ok(f(r)))?; + metadata.as_pre_download_alert_mut().mutate(|alert| { + if let Some(alert) = alert { + f(&mut alert.message); + } + Ok(()) + }) + } } pub async fn get_package_index( @@ -651,6 +676,7 @@ pub(crate) mod tests { fn old_manifest_defaults_hardware_virtualization_to_false() { let metadata = PackageMetadata { title: "Test Package".into(), + default_locale: None, description: Description { short: LocaleString::Translated("Short".into()), long: LocaleString::Translated("Long".into()), @@ -720,7 +746,7 @@ pub(crate) mod tests { ); let mut localized = serde_json::from_value::(encoded).unwrap(); assert_eq!(localized, alert); - localized.message.localize_for("fr_FR"); + localized.message.localize_for(Some("fr_FR"), None); assert_eq!( localized.message, LocaleString::Translated("Sauvegardez avant la mise à jour".into()) diff --git a/shared-libs/crates/start-core/src/registry/sync.rs b/shared-libs/crates/start-core/src/registry/sync.rs index 8986fee2ff..385a45ccc4 100644 --- a/shared-libs/crates/start-core/src/registry/sync.rs +++ b/shared-libs/crates/start-core/src/registry/sync.rs @@ -63,6 +63,9 @@ rpc_toolkit::reflect_ts!(RegistryCache); pub struct OsUpdateCache { pub registry: Url, pub versions: BTreeMap, + /// Tracks the source registry's cached `RegistryInfo::default_locale`. + #[serde(default)] + pub default_locale: Option, #[serde(default)] pub status: RegistryStatus, /// Failure of the latest synchronization attempt; absent while connecting or connected. @@ -290,7 +293,10 @@ fn reconcile( .transpose()? .unwrap_or_default(); indexes.retain(|url, _| desired.contains(&Subscription::Index(url.clone()))); - db.as_private_mut().as_registry_indexes_mut().ser(&indexes) + db.as_private_mut() + .as_registry_indexes_mut() + .ser(&indexes)?; + sync_os_default_locale(db) } async fn watch_registry( @@ -372,6 +378,26 @@ pub(crate) fn next_retry(backoff: &mut u64) -> Duration { delay } +fn sync_os_default_locale(db: &mut DatabaseModel) -> Result<(), Error> { + let public = db.as_public(); + let Some(cache) = public.as_os_update_cache().transpose_ref() else { + return Ok(()); + }; + let registry = cache.as_registry().de()?; + let default_locale = public + .as_registry_cache() + .as_idx(®istry) + .map(|cache| cache.as_info().de().map(|info| info.default_locale)) + .transpose()? + .flatten(); + db.as_public_mut() + .as_os_update_cache_mut() + .transpose_mut() + .unwrap() + .as_default_locale_mut() + .ser(&default_locale) +} + fn set_status( db: &mut DatabaseModel, subscription: &Subscription, @@ -405,6 +431,7 @@ fn set_status( *cache = Some(OsUpdateCache { registry: url.clone(), versions: BTreeMap::new(), + default_locale: None, status, error: error.map(str::to_owned), }); @@ -416,7 +443,7 @@ fn set_status( })?; } } - Ok(()) + sync_os_default_locale(db) } async fn publish( @@ -494,12 +521,13 @@ fn publish_snapshot( .ser(&Some(OsUpdateCache { registry: url.clone(), versions, + default_locale: None, status: RegistryStatus::Connected, error: None, }))?; } } - Ok(()) + sync_os_default_locale(db) } pub(crate) async fn cached_call( diff --git a/shared-libs/crates/start-core/src/registry/sync/polling.rs b/shared-libs/crates/start-core/src/registry/sync/polling.rs index bb388cf1ef..03c1ab6f2a 100644 --- a/shared-libs/crates/start-core/src/registry/sync/polling.rs +++ b/shared-libs/crates/start-core/src/registry/sync/polling.rs @@ -63,6 +63,7 @@ pub(super) fn index(info: RegistryInfo, packages: GetPackagesResponseFull) -> Fu name: info.name, icon: info.icon, description: info.description, + default_locale: info.default_locale, package: PackageIndex { categories: info.categories, packages: packages diff --git a/shared-libs/crates/start-core/src/registry/sync/tests.rs b/shared-libs/crates/start-core/src/registry/sync/tests.rs index 49c2a4a0c9..499d5f8ff1 100644 --- a/shared-libs/crates/start-core/src/registry/sync/tests.rs +++ b/shared-libs/crates/start-core/src/registry/sync/tests.rs @@ -13,6 +13,7 @@ use crate::registry::signer::SignerInfo; use crate::rpc_continuations::Guid; use crate::util::future::NonDetachingJoinHandle; +mod default_locale; mod error_details; mod live; mod live_legacy; diff --git a/shared-libs/crates/start-core/src/registry/sync/tests/default_locale.rs b/shared-libs/crates/start-core/src/registry/sync/tests/default_locale.rs new file mode 100644 index 0000000000..cfa896f73e --- /dev/null +++ b/shared-libs/crates/start-core/src/registry/sync/tests/default_locale.rs @@ -0,0 +1,89 @@ +use super::*; + +fn cached_locale(db: &DatabaseModel) -> Option { + db.as_public() + .as_os_update_cache() + .de() + .unwrap() + .unwrap() + .default_locale +} + +fn publish_index(db: &mut DatabaseModel, index: &FullIndex) { + publish_snapshot( + db, + &Subscription::Index(url()), + &to_value(index).unwrap(), + &device(), + ) + .unwrap(); +} + +#[test] +fn os_default_locale_follows_registry_only_changes_in_either_snapshot_order() { + for order in [ + [Subscription::Index(url()), Subscription::Os(url())], + [Subscription::Os(url()), Subscription::Index(url())], + ] { + let mut db = database(); + let mut index = index(); + index.default_locale = Some("pl_PL".into()); + let full = to_value(&index).unwrap(); + let os = to_value(&index.os).unwrap(); + for subscription in order { + let value = match &subscription { + Subscription::Index(_) => &full, + Subscription::Os(_) => &os, + }; + publish_snapshot(&mut db, &subscription, value, &device()).unwrap(); + } + assert_eq!(cached_locale(&db).as_deref(), Some("pl_PL")); + + for locale in [Some("de_DE"), None] { + index.default_locale = locale.map(Into::into); + publish_index(&mut db, &index); + assert_eq!(cached_locale(&db).as_deref(), locale); + } + } +} + +#[test] +fn disconnecting_the_package_registry_clears_the_os_default_locale() { + let mut db = database(); + let mut index = index(); + index.default_locale = Some("pl_PL".into()); + publish_index(&mut db, &index); + publish_snapshot( + &mut db, + &Subscription::Os(url()), + &to_value(&index.os).unwrap(), + &device(), + ) + .unwrap(); + assert_eq!(cached_locale(&db).as_deref(), Some("pl_PL")); + + db.as_public_mut() + .as_server_info_mut() + .as_registries_mut() + .ser(&crate::trusted_keys::Registries::new()) + .unwrap(); + let desired = subscriptions(&db.as_public().as_server_info().de().unwrap()); + reconcile(&mut db, &desired, false).unwrap(); + assert_eq!(cached_locale(&db), None); +} + +#[test] +fn connecting_os_cache_uses_already_cached_registry_metadata() { + let mut db = database(); + let mut index = index(); + index.default_locale = Some("pl_PL".into()); + publish_index(&mut db, &index); + set_status( + &mut db, + &Subscription::Os(url()), + RegistryStatus::Connecting, + None, + ) + .unwrap(); + assert_eq!(cached_locale(&db).as_deref(), Some("pl_PL")); +} diff --git a/shared-libs/crates/start-core/src/s9pk/v2/compat.rs b/shared-libs/crates/start-core/src/s9pk/v2/compat.rs index ff6381d64e..f5c7266455 100644 --- a/shared-libs/crates/start-core/src/s9pk/v2/compat.rs +++ b/shared-libs/crates/start-core/src/s9pk/v2/compat.rs @@ -255,6 +255,7 @@ impl TryFrom for Manifest { can_migrate_to: VersionRange::none(), metadata: PackageMetadata { title: format!("{} (Legacy)", value.title).into(), + default_locale: None, release_notes: LocaleString::Translated(value.release_notes), pre_download_alert: None, license: value.license.into(), diff --git a/shared-libs/crates/start-core/src/s9pk/v2/manifest.rs b/shared-libs/crates/start-core/src/s9pk/v2/manifest.rs index 7e72fe5ee9..eb0e04160e 100644 --- a/shared-libs/crates/start-core/src/s9pk/v2/manifest.rs +++ b/shared-libs/crates/start-core/src/s9pk/v2/manifest.rs @@ -211,39 +211,43 @@ impl std::str::FromStr for LocaleString { } } impl LocaleString { - pub fn localize_for(&mut self, locale: &str) { + /// Resolves to the requested locale's exact or same-language translation, else the + /// owner's declared default, else an arbitrary stored one. + pub fn localize_for(&mut self, locale: Option<&str>, default: Option<&str>) { if let Self::LanguageMap(map) = self { - if let Some(translated) = map.remove(locale) { - *self = Self::Translated(translated); - return; - } - let prefix = locale.split_inclusive("_").next().unwrap(); - let mut first = None; - for (lang, translated) in std::mem::take(map) { - if lang.starts_with(prefix) { - *self = Self::Translated(translated); - return; - } - if first.is_none() { - first = Some(translated); - } - } - *self = Self::Translated(first.unwrap_or_default()) + let requested = locale + .and_then(|locale| crate::best_locale(locale, map.keys().map(|l| &**l))) + .map(InternedString::intern); + let translated = requested + .and_then(|l| map.remove(&l)) + .or_else(|| default.and_then(|default| map.remove(default))) + .or_else(|| map.values().next().cloned()) + .unwrap_or_default(); + *self = Self::Translated(translated); } } - pub fn localized_for(mut self, locale: &str) -> String { - self.localize_for(locale); + /// Locales of a language map; none for a plain string. + pub fn languages(&self) -> impl Iterator { + match self { + Self::LanguageMap(map) => Some(map.keys()), + Self::Translated(_) => None, + } + .into_iter() + .flatten() + } + pub fn localized_for(mut self, locale: Option<&str>, default: Option<&str>) -> String { + self.localize_for(locale, default); if let Self::Translated(s) = self { s } else { unreachable!() } } - pub fn localize(&mut self) { - self.localize_for(&*rust_i18n::locale()); + pub fn localize(&mut self, default: Option<&str>) { + self.localize_for(Some(&*rust_i18n::locale()), default); } - pub fn localized(self) -> String { - self.localized_for(&*rust_i18n::locale()) + pub fn localized(self, default: Option<&str>) -> String { + self.localized_for(Some(&*rust_i18n::locale()), default) } } impl<'de> Deserialize<'de> for LocaleString { @@ -418,11 +422,6 @@ pub struct Description { rpc_toolkit::reflect_ts!(Description); rpc_toolkit::ts_export!(Description, namespaces = [""]); impl Description { - pub fn localize_for(&mut self, locale: &str) { - self.short.localize_for(locale); - self.long.localize_for(locale); - } - /// The marketplace tile clamps `short` to two lines and hides the rest — /// about 80 characters; the headroom is for locales that need more words /// to say the same thing. `long` is rendered unclamped. @@ -457,6 +456,37 @@ impl Description { } } +#[test] +fn locale_resolution_prefers_requested_then_declared_default() { + let text = || -> LocaleString { + serde_json::from_str(r#"{"en_US":"English","de_DE":"Deutsch","pl_PL":"Polski"}"#).unwrap() + }; + for (locale, default, expected) in [ + (Some("pl_PL"), Some("de_DE"), "Polski"), + (Some("en_GB"), Some("de_DE"), "English"), + (Some("zz_ZZ"), Some("de_DE"), "Deutsch"), + (Some(""), Some("de_DE"), "Deutsch"), + (None, Some("pl_PL"), "Polski"), + (None, Some("de_DE"), "Deutsch"), + ] { + assert_eq!(text().localized_for(locale, default), expected); + } + for locale in [Some("zz_ZZ"), Some(""), None] { + for default in [None, Some("ja_JP")] { + let resolved = text().localized_for(locale, default); + assert!(["English", "Deutsch", "Polski"].contains(&&*resolved)); + } + } + assert_eq!( + LocaleString::LanguageMap(InOMap::default()).localized_for(Some(""), None), + "" + ); + assert_eq!( + LocaleString::Translated("Plain".into()).localized_for(Some("pl_PL"), Some("de_DE")), + "Plain" + ); +} + #[test] fn legacy_emulation_uses_the_image_kept_in_a_cross_arch_backup() { let manifest: Manifest = serde_json::from_value(serde_json::json!({ diff --git a/shared-libs/crates/start-core/src/service/effects/dependency.rs b/shared-libs/crates/start-core/src/service/effects/dependency.rs index 1e27ee19a6..17fdb718a6 100644 --- a/shared-libs/crates/start-core/src/service/effects/dependency.rs +++ b/shared-libs/crates/start-core/src/service/effects/dependency.rs @@ -7,6 +7,7 @@ use exver::VersionRange; use patch_db::ModelExt; use rust_i18n::t; +use crate::db::model::DatabaseModel; use crate::db::model::package::{ CurrentDependencies, CurrentDependencyInfo, CurrentDependencyKind, ManifestPreference, TaskEntry, @@ -511,11 +512,27 @@ pub async fn check_dependencies( ) -> Result, Error> { let context = context.deref()?; let db = context.seed.ctx.db.peek().await; + let manifest = context.seed.persistent_container.s9pk.as_manifest(); + dependency_statuses( + &db, + &context.seed.id, + manifest.metadata.default_locale.as_deref(), + package_ids, + ) +} + +/// Titles use the declaring package's default locale. +fn dependency_statuses( + db: &DatabaseModel, + package_id: &PackageId, + default_locale: Option<&str>, + package_ids: Option>, +) -> Result, Error> { let pde = db .as_public() .as_package_data() - .as_idx(&context.seed.id) - .or_not_found(&context.seed.id)?; + .as_idx(package_id) + .or_not_found(package_id)?; let current_dependencies = pde.as_current_dependencies().de()?; let tasks = pde.as_tasks().de()?; let package_dependency_info: Vec<_> = package_ids @@ -529,16 +546,19 @@ pub async fn check_dependencies( let mut results = Vec::with_capacity(package_dependency_info.len()); for (package_id, dependency_info) in package_dependency_info { - let title = dependency_info.title.clone(); + let title = dependency_info + .title + .clone() + .map(|title| title.localized(default_locale)); + let tasks = tasks + .iter() + .filter(|(_, v)| v.task.package_id == package_id) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); let Some(package) = db.as_public().as_package_data().as_idx(&package_id) else { - let tasks = tasks - .iter() - .filter(|(_, v)| v.task.package_id == package_id) - .map(|(k, v)| (k.clone(), v.clone())) - .collect(); results.push(CheckDependenciesResult { package_id, - title: title.map(|t| t.localized()), + title, installed_version: None, satisfies: BTreeSet::new(), is_running: false, @@ -557,14 +577,9 @@ pub async fn check_dependencies( .transpose_ref() .is_some(); let health_checks = package.as_status_info().as_health().de()?; - let tasks = tasks - .iter() - .filter(|(_, v)| v.task.package_id == package_id) - .map(|(k, v)| (k.clone(), v.clone())) - .collect(); results.push(CheckDependenciesResult { package_id, - title: title.map(|t| t.localized()), + title, installed_version, satisfies, is_running, @@ -627,6 +642,46 @@ pub async fn get_service_manifest( mod test { use super::*; + #[test] + fn dependency_titles_use_the_declaring_package_default_with_or_without_the_dependency() { + let db = Model::from_value(imbl_value::json!({ + "public": { "packageData": { + "caller": { + "currentDependencies": { + "installed": { + "title": { "de_DE": "Deutsch", "pl_PL": "Polski" }, + "kind": "exists", "versionRange": "*", + }, + "missing": { + "title": { "de_DE": "Deutsch", "pl_PL": "Polski" }, + "kind": "exists", "versionRange": "*", + }, + }, + "tasks": {}, + }, + "installed": { + "stateInfo": { + "state": "installed", + "manifest": { + "version": "1.0.0:0", "satisfies": [], "defaultLocale": "pl_PL", + }, + }, + "statusInfo": { "started": null, "health": {} }, + }, + }}, + })); + let caller = "caller".parse().unwrap(); + let results = dependency_statuses(&db, &caller, Some("de_DE"), None).unwrap(); + assert_eq!(results.len(), 2); + for result in results { + assert_eq!(result.title.as_deref(), Some("Deutsch")); + assert_eq!( + result.installed_version.is_some(), + &*result.package_id == "installed" + ); + } + } + #[test] fn required_manifest_requirement_is_the_static_fallback() { let base: crate::dependencies::DepInfo = serde_json::from_str( diff --git a/shared-libs/crates/start-core/src/version/release_notes.rs b/shared-libs/crates/start-core/src/version/release_notes.rs index 332b6acccf..bdebc76d85 100644 --- a/shared-libs/crates/start-core/src/version/release_notes.rs +++ b/shared-libs/crates/start-core/src/version/release_notes.rs @@ -45,7 +45,7 @@ async fn read_update_notes( if ¬es.version != version { return Ok(None); } - let notes = without_pre_update(¬es.release_notes.localized_for(locale)); + let notes = without_pre_update(¬es.release_notes.localized_for(Some(locale), None)); Ok((!notes.trim().is_empty()).then_some(notes)) } diff --git a/shared-libs/ts-modules/marketplace/src/components/about.component.ts b/shared-libs/ts-modules/marketplace/src/components/about.component.ts index 819807f50d..73f1e9a5ce 100644 --- a/shared-libs/ts-modules/marketplace/src/components/about.component.ts +++ b/shared-libs/ts-modules/marketplace/src/components/about.component.ts @@ -73,7 +73,9 @@ import { MarketplaceVersionsComponent } from './versions.component' }
{{ 'Description' | i18n }}
-
+
`, styles: ` diff --git a/shared-libs/ts-modules/marketplace/src/components/dependency.component.ts b/shared-libs/ts-modules/marketplace/src/components/dependency.component.ts index 1b00a60df4..a8c227b380 100644 --- a/shared-libs/ts-modules/marketplace/src/components/dependency.component.ts +++ b/shared-libs/ts-modules/marketplace/src/components/dependency.component.ts @@ -31,7 +31,9 @@ import { MarketplaceIconDirective } from './icon.directive' ({{ 'Required' | i18n }}) } @if (dep().value.description; as description) { - {{ description | localize }} + + {{ description | localize: pkg().defaultLocale }} + } `, @@ -54,6 +56,8 @@ export class MarketplaceDependencyComponent { getTitle(key: string): string { const title = this.pkg().dependencyMetadata[key]?.title - return title ? this.i18nService.localize(title) : key + return title + ? this.i18nService.localize(title, this.pkg().defaultLocale) + : key } } diff --git a/shared-libs/ts-modules/marketplace/src/components/marketplace.component.ts b/shared-libs/ts-modules/marketplace/src/components/marketplace.component.ts index 35381c1101..7e565a6885 100644 --- a/shared-libs/ts-modules/marketplace/src/components/marketplace.component.ts +++ b/shared-libs/ts-modules/marketplace/src/components/marketplace.component.ts @@ -91,7 +91,11 @@ const ICONS: Record = { type="button" (click)="onCategory(cat.key)" > - {{ cat.value.name ? (cat.value.name | localize) : cat.key }} + {{ + cat.value.name + ? (cat.value.name | localize: current()?.info?.defaultLocale) + : cat.key + }} }
@@ -123,7 +127,12 @@ const ICONS: Record = { appearance="info" class="g-markdown" safeLinks - [innerHTML]="description | localize | markdown | dompurify" + [innerHTML]=" + description + | localize: current()?.info?.defaultLocale + | markdown + | dompurify + " >
} @if (warning(); as warning) { @@ -135,7 +144,7 @@ const ICONS: Record = {

@if (current()) { - {{ name() | localize }} + {{ name() | localize: current()?.info?.defaultLocale }} }

diff --git a/shared-libs/ts-modules/marketplace/src/components/release-notes.component.ts b/shared-libs/ts-modules/marketplace/src/components/release-notes.component.ts index eb1ba8175d..f0aff8c72b 100644 --- a/shared-libs/ts-modules/marketplace/src/components/release-notes.component.ts +++ b/shared-libs/ts-modules/marketplace/src/components/release-notes.component.ts @@ -9,7 +9,12 @@ import { MarketplacePkgBase } from '../types' template: `
New in {{ pkg().version }}
`, styles: ` diff --git a/shared-libs/ts-modules/marketplace/src/components/tile.component.ts b/shared-libs/ts-modules/marketplace/src/components/tile.component.ts index cf726c3649..c6926752b8 100644 --- a/shared-libs/ts-modules/marketplace/src/components/tile.component.ts +++ b/shared-libs/ts-modules/marketplace/src/components/tile.component.ts @@ -30,7 +30,9 @@ import { MarketplacePreviewComponent } from './preview.component' {{ pkg().version }} - {{ pkg().description.short | localize }} + + {{ pkg().description.short | localize: pkg().defaultLocale }} + { + const text = { de_DE: 'Deutsch', en_GB: 'English', pl_PL: 'Polski' } + assert.equal(localizeFor(text, 'pl_PL', 'de_DE'), 'Polski') + assert.equal(localizeFor(text, 'en_US', 'de_DE'), 'English') + assert.equal(localizeFor(text, 'fr_FR', 'pl_PL'), 'Polski') + assert.equal(localizeFor(text, 'fr_FR', 'de_DE'), 'Deutsch') + assert.ok(Object.values(text).includes(localizeFor(text, 'fr_FR', 'ja_JP'))) + assert.ok(Object.values(text).includes(localizeFor(text, 'fr_FR'))) + assert.equal(localizeFor({}, 'en_US', 'de_DE'), '') + assert.equal(localizeFor('Plain', 'pl_PL', 'de_DE'), 'Plain') +}) diff --git a/shared-libs/ts-modules/shared/src/i18n/i18n.service.ts b/shared-libs/ts-modules/shared/src/i18n/i18n.service.ts index 6abc72a76d..0e623f0bb6 100644 --- a/shared-libs/ts-modules/shared/src/i18n/i18n.service.ts +++ b/shared-libs/ts-modules/shared/src/i18n/i18n.service.ts @@ -1,6 +1,7 @@ import { inject, Injectable, signal } from '@angular/core' import { TuiLanguageName, TuiLanguageSwitcherService } from '@taiga-ui/i18n' import { I18N, I18N_LOADER, I18N_STORAGE } from './i18n.providers' +import { localizeFor } from './localize' import { T } from '@start9labs/start-core' export const languages = ['en_US', 'es_ES', 'de_DE', 'fr_FR', 'pl_PL'] as const @@ -38,12 +39,8 @@ export class i18nService extends TuiLanguageSwitcherService { ) } - localize(string: T.LocaleString): string { - if (typeof string === 'string') return string - - return ( - string[this.lang] ?? string['en_US'] ?? Object.values(string)[0] ?? '' - ) + localize(string: T.LocaleString, defaultLocale?: string | null): string { + return localizeFor(string, this.lang, defaultLocale) } setLangLocal(language: Languages = 'en_US'): void { diff --git a/shared-libs/ts-modules/shared/src/i18n/localize.pipe.ts b/shared-libs/ts-modules/shared/src/i18n/localize.pipe.ts index 5a0efcedae..a089d139db 100644 --- a/shared-libs/ts-modules/shared/src/i18n/localize.pipe.ts +++ b/shared-libs/ts-modules/shared/src/i18n/localize.pipe.ts @@ -12,8 +12,9 @@ export class LocalizePipe implements PipeTransform { private readonly i18nService = inject(i18nService) private readonly i18n = inject(I18N) - transform(string: T.LocaleString): string { + /** Takes the owning package's or registry's `defaultLocale`. */ + transform(string: T.LocaleString, defaultLocale?: string | null): string { this.i18n() // read signal to trigger change detection on language switch - return this.i18nService.localize(string) + return this.i18nService.localize(string, defaultLocale) } } diff --git a/shared-libs/ts-modules/shared/src/i18n/localize.ts b/shared-libs/ts-modules/shared/src/i18n/localize.ts new file mode 100644 index 0000000000..bdb07a6d87 --- /dev/null +++ b/shared-libs/ts-modules/shared/src/i18n/localize.ts @@ -0,0 +1,25 @@ +import type { T } from '@start9labs/start-core' + +/** + * The requested locale's exact or same-language translation, else the owner's + * declared default, else an arbitrary stored one. + * Matches the backend's `LocaleString::localize_for`. + */ +export function localizeFor( + string: T.LocaleString, + lang: string, + defaultLocale?: string | null, +): string { + if (typeof string === 'string') return string + + const language = lang.split('_')[0] + '_' + return ( + string[lang] ?? + Object.entries(string).find(([locale]) => + locale.startsWith(language), + )?.[1] ?? + (defaultLocale ? string[defaultLocale] : undefined) ?? + Object.values(string)[0] ?? + '' + ) +} diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/effects.schemas.ts b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/effects.schemas.ts index b5d322f237..8d63856935 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/effects.schemas.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/effects.schemas.ts @@ -2350,6 +2350,10 @@ export const NamedHealthCheckResult: z.ZodCodec< }) export const PackageMetadata: z.ZodObject<{ title: z.ZodString + /** + * Locale this package's `LocaleString`s fall back to when a requested one is missing. + */ + defaultLocale: z.ZodOptional> description: typeof Description releaseNotes: typeof LocaleString preDownloadAlert: z.ZodOptional> @@ -2396,6 +2400,13 @@ export const PackageMetadata: z.ZodObject<{ > }> = /* @__PURE__ */ object({ title: z.string(), + /** + * Locale this package's `LocaleString`s fall back to when a requested one is missing. + */ + defaultLocale: z.string().nullable().optional().meta({ + description: + "Locale this package's `LocaleString`s fall back to when a requested one is missing.", + }), description: Description, releaseNotes: LocaleString, preDownloadAlert: PreDownloadAlert.nullable().optional(), diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/registry.schemas.ts b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/registry.schemas.ts index 8c7773978f..449334f180 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/registry.schemas.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/registry.schemas.ts @@ -578,6 +578,11 @@ export const ReplaceOperation: z.ZodObject<{ id: 'ReplaceOperation', description: "JSON Patch 'replace' operation representation", }) +export const SetDefaultLocaleParams: z.ZodObject<{ + defaultLocale: z.ZodNullable +}> = /* @__PURE__ */ object({ defaultLocale: z.string().nullable() }).meta({ + id: 'SetDefaultLocaleParams', +}) export const SetNameParams: z.ZodObject<{ name: z.ZodString }> = /* @__PURE__ */ object({ name: z.string() }).meta({ id: 'SetNameParams', @@ -1099,7 +1104,19 @@ export const PackageIcon: z.ZodUnion = }) export const PackageInfoShort: z.ZodObject<{ releaseNotes: typeof LocaleString -}> = /* @__PURE__ */ object({ releaseNotes: LocaleString }).meta({ + /** + * `PackageMetadata::default_locale`. + */ + defaultLocale: z.ZodOptional> +}> = /* @__PURE__ */ object({ + releaseNotes: LocaleString, + /** + * `PackageMetadata::default_locale`. + */ + defaultLocale: z.string().nullable().optional().meta({ + description: '`PackageMetadata::default_locale`.', + }), +}).meta({ id: 'PackageInfoShort', }) export const PackageReaderParams: z.ZodObject<{ @@ -1378,6 +1395,13 @@ export const SubscribeIndexParams: z.ZodIntersection< z.ZodOptional>, z.ZodNullable > + /** + * Locale to resolve localized text to; one the index lacks gets the fallback. Omission keeps every translation. + */ + language: z.ZodCodec< + z.ZodOptional>, + z.ZodNullable + > }>, typeof ReaderParams > = /* @__PURE__ */ z @@ -1394,6 +1418,16 @@ export const SubscribeIndexParams: z.ZodIntersection< description: 'Client StartOS version. Omission preserves the canonical index format.', }), + /** + * Locale to resolve localized text to; one the index lacks gets the fallback. Omission keeps every translation. + */ + language: wire( + z.string().nullable().optional(), + z.string().nullable(), + ).meta({ + description: + 'Locale to resolve localized text to; one the index lacks gets the fallback. Omission keeps every translation.', + }), }), ReaderParams, ) @@ -1467,6 +1501,10 @@ export const PackageAccess: z.ZodObject<{ }) export const PackageMetadata: z.ZodObject<{ title: z.ZodString + /** + * Locale this package's `LocaleString`s fall back to when a requested one is missing. + */ + defaultLocale: z.ZodOptional> description: typeof Description releaseNotes: typeof LocaleString preDownloadAlert: z.ZodOptional> @@ -1513,6 +1551,13 @@ export const PackageMetadata: z.ZodObject<{ > }> = /* @__PURE__ */ object({ title: z.string(), + /** + * Locale this package's `LocaleString`s fall back to when a requested one is missing. + */ + defaultLocale: z.string().nullable().optional().meta({ + description: + "Locale this package's `LocaleString`s fall back to when a requested one is missing.", + }), description: Description, releaseNotes: LocaleString, preDownloadAlert: PreDownloadAlert.nullable().optional(), @@ -1575,6 +1620,13 @@ export const RegistryInfo: z.ZodObject<{ z.ZodOptional>, z.ZodNullable > + /** + * `FullIndex::default_locale`. + */ + defaultLocale: z.ZodCodec< + z.ZodOptional>, + z.ZodNullable + > categories: z.ZodRecord /** * Registry-selected signers, not an assertion of trust. @@ -1595,6 +1647,15 @@ export const RegistryInfo: z.ZodObject<{ ).meta({ description: "Markdown, shown above the registry's services.", }), + /** + * `FullIndex::default_locale`. + */ + defaultLocale: wire( + z.string().nullable().optional(), + z.string().nullable(), + ).meta({ + description: '`FullIndex::default_locale`.', + }), categories: z.record(z.string(), Category), /** * Registry-selected signers, not an assertion of trust. @@ -1755,6 +1816,13 @@ export const FullIndex: z.ZodObject<{ z.ZodOptional>, z.ZodNullable > + /** + * Locale registry-owned `LocaleString`s fall back to when a requested one is missing. + */ + defaultLocale: z.ZodCodec< + z.ZodOptional>, + z.ZodNullable + > package: typeof PackageIndex os: typeof OsIndex signers: z.ZodRecord @@ -1769,6 +1837,16 @@ export const FullIndex: z.ZodObject<{ LocaleString.nullable().optional(), LocaleString.nullable(), ), + /** + * Locale registry-owned `LocaleString`s fall back to when a requested one is missing. + */ + defaultLocale: wire( + z.string().nullable().optional(), + z.string().nullable(), + ).meta({ + description: + 'Locale registry-owned `LocaleString`s fall back to when a requested one is missing.', + }), package: PackageIndex, os: OsIndex, signers: z.record(z.string(), SignerInfo), @@ -1901,6 +1979,23 @@ export const Api = { _ITEM: /* @__PURE__ */ z.never(), _FINAL: /* @__PURE__ */ z.null(), _CHILDREN: { + 'set-default-locale': { + _PARAMS: /* @__PURE__ */ z.intersection( + z.intersection( + object({ + format: wire( + IoFormat.nullable().optional(), + IoFormat.nullable(), + ), + }), + empty, + ), + SetDefaultLocaleParams, + ), + _RETURN: /* @__PURE__ */ z.null(), + _ITEM: /* @__PURE__ */ z.never(), + _FINAL: /* @__PURE__ */ z.null(), + }, 'set-description': { _PARAMS: /* @__PURE__ */ z.intersection( z.intersection( diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/registry.ts b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/registry.ts index cc61192907..9beb699acf 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/registry.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/registry.ts @@ -194,6 +194,9 @@ export type RemoveVersionParamsInput = z.input< * JSON Patch 'replace' operation representation */ export type ReplaceOperation = z.output +export type SetDefaultLocaleParamsInput = z.input< + typeof schemas.SetDefaultLocaleParams +> export type SetNameParamsInput = z.input /** diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.schemas.ts b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.schemas.ts index c10f2075ac..959346efe8 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.schemas.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.schemas.ts @@ -1435,6 +1435,11 @@ export const SetCountryParams: z.ZodObject<{ country: z.ZodString }> = /* @__PURE__ */ object({ country: z.string() }).meta({ id: 'SetCountryParams', }) +export const SetDefaultLocaleParams: z.ZodObject<{ + defaultLocale: z.ZodNullable +}> = /* @__PURE__ */ object({ defaultLocale: z.string().nullable() }).meta({ + id: 'SetDefaultLocaleParams', +}) export const SetEchoipUrlsParams: z.ZodObject<{ urls: z.ZodArray }> = /* @__PURE__ */ object({ urls: z.array(z.string()) }).meta({ @@ -3585,7 +3590,19 @@ export const PackageIdParams: z.ZodObject<{ id: typeof PackageId }> = }) export const PackageInfoShort: z.ZodObject<{ releaseNotes: typeof LocaleString -}> = /* @__PURE__ */ object({ releaseNotes: LocaleString }).meta({ + /** + * `PackageMetadata::default_locale`. + */ + defaultLocale: z.ZodOptional> +}> = /* @__PURE__ */ object({ + releaseNotes: LocaleString, + /** + * `PackageMetadata::default_locale`. + */ + defaultLocale: z.string().nullable().optional().meta({ + description: '`PackageMetadata::default_locale`.', + }), +}).meta({ id: 'PackageInfoShort', }) export const PackageReaderParams: z.ZodObject<{ @@ -4413,6 +4430,13 @@ export const SubscribeIndexParams: z.ZodIntersection< z.ZodOptional>, z.ZodNullable > + /** + * Locale to resolve localized text to; one the index lacks gets the fallback. Omission keeps every translation. + */ + language: z.ZodCodec< + z.ZodOptional>, + z.ZodNullable + > }>, typeof ReaderParams > = /* @__PURE__ */ z @@ -4429,6 +4453,16 @@ export const SubscribeIndexParams: z.ZodIntersection< description: 'Client StartOS version. Omission preserves the canonical index format.', }), + /** + * Locale to resolve localized text to; one the index lacks gets the fallback. Omission keeps every translation. + */ + language: wire( + z.string().nullable().optional(), + z.string().nullable(), + ).meta({ + description: + 'Locale to resolve localized text to; one the index lacks gets the fallback. Omission keeps every translation.', + }), }), ReaderParams, ) @@ -5177,6 +5211,10 @@ export const PackageAccess: z.ZodObject<{ }) export const PackageMetadata: z.ZodObject<{ title: z.ZodString + /** + * Locale this package's `LocaleString`s fall back to when a requested one is missing. + */ + defaultLocale: z.ZodOptional> description: typeof Description releaseNotes: typeof LocaleString preDownloadAlert: z.ZodOptional> @@ -5223,6 +5261,13 @@ export const PackageMetadata: z.ZodObject<{ > }> = /* @__PURE__ */ object({ title: z.string(), + /** + * Locale this package's `LocaleString`s fall back to when a requested one is missing. + */ + defaultLocale: z.string().nullable().optional().meta({ + description: + "Locale this package's `LocaleString`s fall back to when a requested one is missing.", + }), description: Description, releaseNotes: LocaleString, preDownloadAlert: PreDownloadAlert.nullable().optional(), @@ -5362,6 +5407,13 @@ export const RegistryInfo: z.ZodObject<{ z.ZodOptional>, z.ZodNullable > + /** + * `FullIndex::default_locale`. + */ + defaultLocale: z.ZodCodec< + z.ZodOptional>, + z.ZodNullable + > categories: z.ZodRecord /** * Registry-selected signers, not an assertion of trust. @@ -5382,6 +5434,15 @@ export const RegistryInfo: z.ZodObject<{ ).meta({ description: "Markdown, shown above the registry's services.", }), + /** + * `FullIndex::default_locale`. + */ + defaultLocale: wire( + z.string().nullable().optional(), + z.string().nullable(), + ).meta({ + description: '`FullIndex::default_locale`.', + }), categories: z.record(z.string(), Category), /** * Registry-selected signers, not an assertion of trust. @@ -6313,6 +6374,13 @@ export const FullIndex: z.ZodObject<{ z.ZodOptional>, z.ZodNullable > + /** + * Locale registry-owned `LocaleString`s fall back to when a requested one is missing. + */ + defaultLocale: z.ZodCodec< + z.ZodOptional>, + z.ZodNullable + > package: typeof PackageIndex os: typeof OsIndex signers: z.ZodRecord @@ -6327,6 +6395,16 @@ export const FullIndex: z.ZodObject<{ LocaleString.nullable().optional(), LocaleString.nullable(), ), + /** + * Locale registry-owned `LocaleString`s fall back to when a requested one is missing. + */ + defaultLocale: wire( + z.string().nullable().optional(), + z.string().nullable(), + ).meta({ + description: + 'Locale registry-owned `LocaleString`s fall back to when a requested one is missing.', + }), package: PackageIndex, os: OsIndex, signers: z.record(z.string(), SignerInfo), @@ -7753,6 +7831,26 @@ export const Api = { _ITEM: /* @__PURE__ */ z.never(), _FINAL: /* @__PURE__ */ z.null(), _CHILDREN: { + 'set-default-locale': { + _PARAMS: /* @__PURE__ */ z.intersection( + z.intersection( + z.intersection(empty, RegistryUrlParams), + z.intersection( + object({ + format: wire( + IoFormat.nullable().optional(), + IoFormat.nullable(), + ), + }), + empty, + ), + ), + SetDefaultLocaleParams, + ), + _RETURN: /* @__PURE__ */ z.null(), + _ITEM: /* @__PURE__ */ z.never(), + _FINAL: /* @__PURE__ */ z.null(), + }, 'set-description': { _PARAMS: /* @__PURE__ */ z.intersection( z.intersection( diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.ts b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.ts index d97d40132a..4f89447946 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.ts @@ -378,6 +378,9 @@ export type ServiceInterfaceId = z.output export type ServiceInterfaceType = z.output export type Session = z.output export type SetCountryParamsInput = z.input +export type SetDefaultLocaleParamsInput = z.input< + typeof schemas.SetDefaultLocaleParams +> export type SetEchoipUrlsParamsInput = z.input< typeof schemas.SetEchoipUrlsParams > diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts b/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts index ae2ad80ca6..97f5bb262c 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts @@ -1574,6 +1574,11 @@ export const SetDataVersionParams: z.ZodObject<{ }).meta({ id: 'SetDataVersionParams', }) +export const SetDefaultLocaleParams: z.ZodObject<{ + defaultLocale: z.ZodNullable +}> = /* @__PURE__ */ object({ defaultLocale: z.string().nullable() }).meta({ + id: 'SetDefaultLocaleParams', +}) export const SetLanguageParams: z.ZodObject<{ language: z.ZodString }> = /* @__PURE__ */ object({ language: z.string() }).meta({ id: 'SetLanguageParams', @@ -4032,7 +4037,19 @@ export const PackageIcon: z.ZodUnion = }) export const PackageInfoShort: z.ZodObject<{ releaseNotes: typeof LocaleString -}> = /* @__PURE__ */ object({ releaseNotes: LocaleString }).meta({ + /** + * `PackageMetadata::default_locale`. + */ + defaultLocale: z.ZodOptional> +}> = /* @__PURE__ */ object({ + releaseNotes: LocaleString, + /** + * `PackageMetadata::default_locale`. + */ + defaultLocale: z.string().nullable().optional().meta({ + description: '`PackageMetadata::default_locale`.', + }), +}).meta({ id: 'PackageInfoShort', }) export const PackageReaderParams: z.ZodObject<{ @@ -5669,6 +5686,13 @@ export const NutConfig: z.ZodObject<{ export const OsUpdateCache: z.ZodObject<{ registry: z.ZodString versions: z.ZodRecord + /** + * Tracks the source registry's cached `RegistryInfo::default_locale`. + */ + defaultLocale: z.ZodCodec< + z.ZodOptional>, + z.ZodNullable + > status: z.ZodCodec< z.ZodOptional, typeof RegistryStatus @@ -5680,6 +5704,16 @@ export const OsUpdateCache: z.ZodObject<{ }> = /* @__PURE__ */ object({ registry: z.string(), versions: z.record(z.string(), OsVersionInfo), + /** + * Tracks the source registry's cached `RegistryInfo::default_locale`. + */ + defaultLocale: wire( + z.string().nullable().optional(), + z.string().nullable(), + ).meta({ + description: + "Tracks the source registry's cached `RegistryInfo::default_locale`.", + }), status: wire(RegistryStatus.optional(), RegistryStatus), /** * Failure of the latest synchronization attempt; absent while connecting or connected. @@ -5707,6 +5741,10 @@ export const PackageAccess: z.ZodObject<{ }) export const PackageMetadata: z.ZodObject<{ title: z.ZodString + /** + * Locale this package's `LocaleString`s fall back to when a requested one is missing. + */ + defaultLocale: z.ZodOptional> description: typeof Description releaseNotes: typeof LocaleString preDownloadAlert: z.ZodOptional> @@ -5753,6 +5791,13 @@ export const PackageMetadata: z.ZodObject<{ > }> = /* @__PURE__ */ object({ title: z.string(), + /** + * Locale this package's `LocaleString`s fall back to when a requested one is missing. + */ + defaultLocale: z.string().nullable().optional().meta({ + description: + "Locale this package's `LocaleString`s fall back to when a requested one is missing.", + }), description: Description, releaseNotes: LocaleString, preDownloadAlert: PreDownloadAlert.nullable().optional(), @@ -5935,6 +5980,13 @@ export const RegistryInfo: z.ZodObject<{ z.ZodOptional>, z.ZodNullable > + /** + * `FullIndex::default_locale`. + */ + defaultLocale: z.ZodCodec< + z.ZodOptional>, + z.ZodNullable + > categories: z.ZodRecord /** * Registry-selected signers, not an assertion of trust. @@ -5955,6 +6007,15 @@ export const RegistryInfo: z.ZodObject<{ ).meta({ description: "Markdown, shown above the registry's services.", }), + /** + * `FullIndex::default_locale`. + */ + defaultLocale: wire( + z.string().nullable().optional(), + z.string().nullable(), + ).meta({ + description: '`FullIndex::default_locale`.', + }), categories: z.record(z.string(), Category), /** * Registry-selected signers, not an assertion of trust. @@ -7345,6 +7406,13 @@ export const FullIndex: z.ZodObject<{ z.ZodOptional>, z.ZodNullable > + /** + * Locale registry-owned `LocaleString`s fall back to when a requested one is missing. + */ + defaultLocale: z.ZodCodec< + z.ZodOptional>, + z.ZodNullable + > package: typeof PackageIndex os: typeof OsIndex signers: z.ZodRecord @@ -7359,6 +7427,16 @@ export const FullIndex: z.ZodObject<{ LocaleString.nullable().optional(), LocaleString.nullable(), ), + /** + * Locale registry-owned `LocaleString`s fall back to when a requested one is missing. + */ + defaultLocale: wire( + z.string().nullable().optional(), + z.string().nullable(), + ).meta({ + description: + 'Locale registry-owned `LocaleString`s fall back to when a requested one is missing.', + }), package: PackageIndex, os: OsIndex, signers: z.record(z.string(), SignerInfo), diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/types.ts b/shared-libs/ts-modules/start-core/lib/osBindings/types.ts index 07086d3c4d..62ce329bc4 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/types.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/types.ts @@ -460,6 +460,12 @@ export type SetDataVersionParams = z.output export type SetDataVersionParamsInput = z.input< typeof schemas.SetDataVersionParams > +export type SetDefaultLocaleParams = z.output< + typeof schemas.SetDefaultLocaleParams +> +export type SetDefaultLocaleParamsInput = z.input< + typeof schemas.SetDefaultLocaleParams +> export type SetLanguageParams = z.output export type SetLanguageParamsInput = z.input export type SetMainStatusStatus = z.output From a323e31a592106e1855e561da0bf90dcd7a336f8 Mon Sep 17 00:00:00 2001 From: StuPleb Date: Wed, 18 Nov 2026 19:10:28 +0100 Subject: [PATCH 02/38] fix(web): show release notes in full and open their links in a new tab (#4768) The release-notes card capped itself at 30rem and hid its own scrollbar, so longer notes looked cut off inside a drawer that already scrolls. It now grows to fit, like the Description card above it. The notes render with the shared g-markdown styles, so a wide code block scrolls on its own instead of being clipped by the card, and long URLs wrap. They also gain safeLinks, as every other rendered-markdown surface has, so an external link opens in a new tab instead of replacing the UI. Co-authored-by: Claude Opus 5.5 Co-authored-by: helix-red <355572797+helix-red@users.noreply.github.com> --- .../patch-fixed-release-notes-height.md | 5 +++++ .../src/components/release-notes.component.ts | 22 ++++++++++++++----- 2 files changed, 21 insertions(+), 6 deletions(-) create mode 100644 projects/start-os/changelog/patch-fixed-release-notes-height.md diff --git a/projects/start-os/changelog/patch-fixed-release-notes-height.md b/projects/start-os/changelog/patch-fixed-release-notes-height.md new file mode 100644 index 0000000000..5089bf52c4 --- /dev/null +++ b/projects/start-os/changelog/patch-fixed-release-notes-height.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Show a package's release notes in full in the marketplace and Updates sidebars and on the sideload page, and open their links in a new tab. diff --git a/shared-libs/ts-modules/marketplace/src/components/release-notes.component.ts b/shared-libs/ts-modules/marketplace/src/components/release-notes.component.ts index f0aff8c72b..d99ddf29fb 100644 --- a/shared-libs/ts-modules/marketplace/src/components/release-notes.component.ts +++ b/shared-libs/ts-modules/marketplace/src/components/release-notes.component.ts @@ -1,5 +1,9 @@ import { Component, input } from '@angular/core' -import { LocalizePipe, MarkdownPipe } from '@start9labs/shared' +import { + LocalizePipe, + MarkdownPipe, + SafeLinksDirective, +} from '@start9labs/shared' import { NgDompurifyPipe } from '@taiga-ui/dompurify' import { TuiCardLarge, TuiHeader } from '@taiga-ui/layout' import { MarketplacePkgBase } from '../types' @@ -9,6 +13,8 @@ import { MarketplacePkgBase } from '../types' template: `
New in {{ pkg().version }}
match[1]), [server]) diff --git a/projects/start-os/changelog/patch-fixed-vpn-dns-bypass.md b/projects/start-os/changelog/patch-fixed-vpn-dns-bypass.md new file mode 100644 index 0000000000..89b8dd41e1 --- /dev/null +++ b/projects/start-os/changelog/patch-fixed-vpn-dns-bypass.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- DNS servers supplied by a VPN gateway no longer bypass the StartOS resolver for host lookups such as clock synchronization. diff --git a/projects/start-os/debian/postinst b/projects/start-os/debian/postinst index f9794c5c67..9248c679c1 100755 --- a/projects/start-os/debian/postinst +++ b/projects/start-os/debian/postinst @@ -143,10 +143,12 @@ rm -f "$resolv_conf" echo "nameserver 127.0.0.1" > "$resolv_conf" echo "#" > /etc/network/interfaces +# The StartOS resolver is the only host DNS path; NetworkManager publishes no resolver config. cat << EOF > /etc/NetworkManager/NetworkManager.conf [main] plugins=ifupdown,keyfile dns=none +systemd-resolved=false [ifupdown] managed=true From 09ed246ef38196b36c485f6fabeaadbad9f6ed86 Mon Sep 17 00:00:00 2001 From: Dominion5254 Date: Wed, 18 Nov 2026 12:42:30 -0700 Subject: [PATCH 04/38] fix(start-os): keep streams a re-addressed vhost target still accepts (#4764) A vhost target's identity includes the addresses it accepts on, so any change to that set (a gateway added or removed, an address switched off) replaced the target, and replacing a target cancelled every stream proxied through it. Deleting a WireGuard gateway therefore cut the admin UI's own connection while the deletion RPC was still in flight. The browser resent the signed POST on a fresh connection, the nonce cache rejected the resend, and a delete that had succeeded reported "replay attack detected". A target that differs from its predecessor only in what it accepts now takes over the predecessor's entry in place. Each stream records where it arrived, and the takeover cancels only the streams the new target rejects. Streams that register afterwards, such as a TLS handshake already in flight, are checked against the new target as well, so switching an address off still ends its streams immediately. The plaintext proxy is retargeted the same way. A change to how streams are relayed, or an entry another owner shares, still replaces the target and cancels its streams. --- ...xed-connections-survive-address-changes.md | 5 + .../start-core/src/net/net_controller.rs | 63 +-- .../crates/start-core/src/net/vhost.rs | 370 ++++++++++++++---- .../src/net/vhost/plain_http_tests.rs | 44 +++ 4 files changed, 381 insertions(+), 101 deletions(-) create mode 100644 projects/start-os/changelog/patch-fixed-connections-survive-address-changes.md diff --git a/projects/start-os/changelog/patch-fixed-connections-survive-address-changes.md b/projects/start-os/changelog/patch-fixed-connections-survive-address-changes.md new file mode 100644 index 0000000000..60adf13911 --- /dev/null +++ b/projects/start-os/changelog/patch-fixed-connections-survive-address-changes.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Adding, removing or reconfiguring a gateway, or switching an address off, no longer disconnects open sessions on the addresses that remain enabled. Deleting a gateway no longer reports an error after it succeeds. diff --git a/shared-libs/crates/start-core/src/net/net_controller.rs b/shared-libs/crates/start-core/src/net/net_controller.rs index f9c1412815..5b88a3139c 100644 --- a/shared-libs/crates/start-core/src/net/net_controller.rs +++ b/shared-libs/crates/start-core/src/net/net_controller.rs @@ -505,8 +505,8 @@ fn retired_hosts<'a>(held: impl Iterator, current: &Hosts) -> #[derive(Debug)] enum ProxyHandle { - Tls { _owner: Arc<()> }, - Plaintext { _server: PlainHttpProxy }, + Tls { owner: Arc<()> }, + Plaintext { server: PlainHttpProxy }, } #[derive(Default, Debug)] @@ -988,32 +988,43 @@ impl NetServiceData { .cloned() .collect::>(); for key in all { - let mut prev = binds.vhosts.remove(&key); + let prev = binds.vhosts.remove(&key); if let Some(target) = vhosts.remove(&key) { - prev = prev.filter(|(t, _)| t == &target); - binds.vhosts.insert( - key.clone(), - if let Some(prev) = prev { - prev - } else { - ( - target.clone(), - if http_ports.contains(&key.1) { - ProxyHandle::Plaintext { - _server: ctrl.vhost.plaintext_proxy(key.1, target), - } - } else { - ProxyHandle::Tls { - _owner: ctrl.vhost.add( - key.0, - key.1, - DynVHostTarget::new(target), - )?, - } - }, - ) + let plaintext = http_ports.contains(&key.1); + let handle = match prev { + Some((prev, handle)) if prev == target => handle, + Some((prev, ProxyHandle::Tls { owner })) if !plaintext => ProxyHandle::Tls { + owner: ctrl.vhost.replace( + key.0.clone(), + key.1, + &DynVHostTarget::new(prev), + owner, + DynVHostTarget::new(target.clone()), + )?, }, - ); + Some((_, ProxyHandle::Plaintext { server })) + if plaintext && server.retarget(&target) => + { + ProxyHandle::Plaintext { server } + } + prev => { + drop(prev); + if plaintext { + ProxyHandle::Plaintext { + server: ctrl.vhost.plaintext_proxy(key.1, target.clone()), + } + } else { + ProxyHandle::Tls { + owner: ctrl.vhost.add( + key.0.clone(), + key.1, + DynVHostTarget::new(target.clone()), + )?, + } + } + } + }; + binds.vhosts.insert(key, (target, handle)); } else { if let Some((_, handle)) = prev { let tls = matches!(handle, ProxyHandle::Tls { .. }); diff --git a/shared-libs/crates/start-core/src/net/vhost.rs b/shared-libs/crates/start-core/src/net/vhost.rs index 8b8ac56805..c308e01b21 100644 --- a/shared-libs/crates/start-core/src/net/vhost.rs +++ b/shared-libs/crates/start-core/src/net/vhost.rs @@ -57,7 +57,7 @@ use crate::util::collections::EqSet; use crate::util::future::NonDetachingJoinHandle; use crate::util::io::ReadWriter; use crate::util::serde::{HandlerExtSerde, MaybeUtf8String, display_serializable}; -use crate::util::sync::{SyncMutex, Watch}; +use crate::util::sync::{SyncMutex, SyncRwLock, Watch}; use crate::{GatewayId, HOST_IP, HostId, PackageId, ResultExt}; /// Identifies which service+host contributed a set of SNI hostname mappings, so @@ -337,6 +337,28 @@ impl VHostController { }) } + /// The owner must be the one `add` returned for the replaced target. + #[instrument(skip_all)] + pub fn replace( + &self, + hostname: Option, + external: u16, + prev: &DynVHostTarget, + owner: Arc<()>, + next: DynVHostTarget, + ) -> Result, Error> { + self.servers.mutate(|writable| { + let server = if let Some(server) = writable.remove(&external) { + server + } else { + self.create_server(external) + }; + let rc = server.replace(hostname, prev, owner, next, self.max_proxy_conns_per_target); + writable.insert(external, server); + Ok(rc?) + }) + } + /// Once per name until a certificate lands: the address refuses /// connections meanwhile, and nothing else would say why. fn report_acme_failure(&self) -> ReportOrderFailure { @@ -935,6 +957,16 @@ pub trait VHostTarget: std::fmt::Debug + Eq { fn filter_private(&self, metadata: &::Metadata) -> bool { false } + /// Whether an established stream may stay on this target. + #[allow(unused_variables)] + fn admits(&self, arrival: &Arrival) -> bool { + true + } + /// Whether the two relay a stream identically. + #[allow(unused_variables)] + fn routes_like(&self, other: &Self) -> bool { + false + } fn acme(&self) -> Option<&AcmeProvider> { None } @@ -963,6 +995,8 @@ pub trait VHostTarget: std::fmt::Debug + Eq { pub trait DynVHostTargetT: std::fmt::Debug + Any { fn filter(&self, metadata: &::Metadata) -> bool; fn filter_private(&self, metadata: &::Metadata) -> bool; + fn admits(&self, arrival: &Arrival) -> bool; + fn routes_like(&self, other: &dyn DynVHostTargetT) -> bool; fn acme(&self) -> Option<&AcmeProvider>; fn bind_requirements(&self) -> (BTreeSet, BTreeSet); fn is_passthrough(&self) -> bool; @@ -990,6 +1024,14 @@ impl + 'static> DynVHostTargetT for T { fn filter_private(&self, metadata: &::Metadata) -> bool { VHostTarget::filter_private(self, metadata) } + fn admits(&self, arrival: &Arrival) -> bool { + >::admits(self, arrival) + } + fn routes_like(&self, other: &dyn DynVHostTargetT) -> bool { + (other as &dyn Any) + .downcast_ref() + .is_some_and(|other| >::routes_like(self, other)) + } fn acme(&self) -> Option<&AcmeProvider> { VHostTarget::acme(self) } @@ -1116,19 +1158,11 @@ pub struct ProxyTarget { } impl PartialEq for ProxyTarget { fn eq(&self, other: &Self) -> bool { - self.public_v4 == other.public_v4 + self.same_route(other) + && self.public_v4 == other.public_v4 && self.public_v6 == other.public_v6 && self.public_v6_gateways == other.public_v6_gateways && self.private == other.private - && self.acme == other.acme - && self.addr == other.addr - && self.addr_v6 == other.addr_v6 - && self.proxy == other.proxy - && self.passthrough == other.passthrough - && self.preserve_source_ip == other.preserve_source_ip - && self.alpn == other.alpn - && self.connect_ssl.as_ref().map(Arc::as_ptr) - == other.connect_ssl.as_ref().map(Arc::as_ptr) } } impl Eq for ProxyTarget {} @@ -1192,6 +1226,23 @@ impl ProxyTarget { wan || self.accepts_as_private(subnets, src, dst) } + fn accepts_arrival(&self, at: &Arrival) -> bool { + self.accepts(&at.gateway, &at.subnets, at.src, at.dst) + } + + /// Whether the two differ at most in which arrivals they accept. + fn same_route(&self, other: &Self) -> bool { + self.acme == other.acme + && self.addr == other.addr + && self.addr_v6 == other.addr_v6 + && self.proxy == other.proxy + && self.passthrough == other.passthrough + && self.preserve_source_ip == other.preserve_source_ip + && self.alpn == other.alpn + && self.connect_ssl.as_ref().map(Arc::as_ptr) + == other.connect_ssl.as_ref().map(Arc::as_ptr) + } + /// A dial of one of our own private addresses from that address's network. /// On IPv4 the source is all that separates it from a forwarded one. fn accepts_as_private(&self, subnets: &OrdSet, src: IpAddr, dst: IpAddr) -> bool { @@ -1351,7 +1402,8 @@ impl ProxyTarget { } } -struct Arrival { +#[derive(Debug)] +pub struct Arrival { gateway: GatewayId, subnets: OrdSet, src: IpAddr, @@ -1390,10 +1442,7 @@ where { type PreprocessRes = (AcceptStream, Option); fn filter(&self, metadata: &::Metadata) -> bool { - let Some(at) = arrival::(metadata) else { - return false; - }; - self.accepts(&at.gateway, &at.subnets, at.src, at.dst) + arrival::(metadata).is_some_and(|at| self.accepts_arrival(&at)) } fn filter_private(&self, metadata: &::Metadata) -> bool { let Some(at) = arrival::(metadata) else { @@ -1401,6 +1450,12 @@ where }; self.accepts_as_private(&at.subnets, at.src, at.dst) } + fn admits(&self, arrival: &Arrival) -> bool { + self.accepts_arrival(arrival) + } + fn routes_like(&self, other: &Self) -> bool { + self.same_route(other) + } fn acme(&self) -> Option<&AcmeProvider> { self.acme.as_ref() } @@ -1501,7 +1556,8 @@ where ctx: ProxyContext, ) { let target = self.clone(); - let (stream, registration, conn_cancel) = ctx.track_with(stream); + let (stream, registration, conn_cancel) = + ctx.track_with(stream, arrival::(&metadata.inner)); tokio::spawn(async move { let _registration = registration; let _origin_registration = origin_registration; @@ -1604,30 +1660,56 @@ impl AsyncWrite for ActivityStream { struct ConnEntry { last_active: Arc, cancel: CancellationToken, + arrival: Option, +} + +type Admission = Arc bool + Send + Sync>; + +#[derive(Default)] +struct Conns { + entries: HashMap, + admission: Option, } /// Per-target proxy-task registry with LRU eviction at the cap. -#[derive(Debug)] pub struct ConnRegistry { cap: usize, next_id: AtomicU64, - entries: SyncMutex>, + conns: SyncMutex, +} +impl fmt::Debug for ConnRegistry { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ConnRegistry") + .field("cap", &self.cap) + .finish_non_exhaustive() + } } impl ConnRegistry { pub fn new(cap: usize) -> Arc { Arc::new(Self { cap, next_id: AtomicU64::new(0), - entries: SyncMutex::new(HashMap::new()), + conns: SyncMutex::new(Conns::default()), }) } fn register( self: &Arc, last_active: Arc, cancel: CancellationToken, + arrival: Option, ) -> ConnRegHandle { let id = self.next_id.fetch_add(1, Ordering::Relaxed); - self.entries.mutate(|m| { + self.conns.mutate(|conns| { + let admitted = match (&conns.admission, &arrival) { + (None, _) => true, + (Some(admits), Some(at)) => admits(at), + (Some(_), None) => false, + }; + if !admitted { + cancel.cancel(); + return; + } + let m = &mut conns.entries; if m.len() >= self.cap { if let Some((victim_id, victim)) = m .iter() @@ -1643,6 +1725,7 @@ impl ConnRegistry { ConnEntry { last_active, cancel, + arrival, }, ); }); @@ -1651,9 +1734,22 @@ impl ConnRegistry { registry: Arc::downgrade(self), } } + /// Cancels each stream the predicate rejects, including streams registered later. + fn readmit(&self, admits: Admission) { + self.conns.mutate(|conns| { + conns.entries.retain(|_, entry| { + let kept = entry.arrival.as_ref().is_some_and(|at| admits(at)); + if !kept { + entry.cancel.cancel(); + } + kept + }); + conns.admission = Some(admits); + }); + } #[cfg(test)] fn len(&self) -> usize { - self.entries.peek(|m| m.len()) + self.conns.peek(|c| c.entries.len()) } } @@ -1664,8 +1760,8 @@ pub struct ConnRegHandle { impl Drop for ConnRegHandle { fn drop(&mut self) { if let Some(r) = self.registry.upgrade() { - r.entries.mutate(|m| { - m.remove(&self.id); + r.conns.mutate(|c| { + c.entries.remove(&self.id); }); } } @@ -1687,18 +1783,19 @@ impl ProxyContext { let last_active = Arc::new(AtomicU64::new(monotonic_millis())); let handle = self .registry - .register(last_active.clone(), self.cancel.child_token()); + .register(last_active.clone(), self.cancel.child_token(), None); (ActivityStream::new(stream, last_active), handle) } pub fn track_with( &self, stream: AcceptStream, + arrival: Option, ) -> (AcceptStream, ConnRegHandle, CancellationToken) { let last_active = Arc::new(AtomicU64::new(monotonic_millis())); let conn_cancel = self.cancel.child_token(); let handle = self .registry - .register(last_active.clone(), conn_cancel.clone()); + .register(last_active.clone(), conn_cancel.clone(), arrival); let wrapped: Pin> = Box::pin(ActivityStream::new(stream, last_active)); (wrapped, handle, conn_cancel) @@ -1706,7 +1803,9 @@ impl ProxyContext { } pub struct PlainHttpProxy { - cancel: CancellationToken, + target: Arc>, + requirements: Watch, + ctx: ProxyContext, _thread: NonDetachingJoinHandle<()>, } @@ -1725,12 +1824,7 @@ impl PlainHttpProxy { target: ProxyTarget, max_connections: usize, ) -> Self { - let (public_gateways, private_ips) = - VHostTarget::::bind_requirements(&target); - let requirements = Watch::new(VHostBindRequirements { - public_gateways, - private_ips, - }); + let requirements = Watch::new(Self::requirements(&target)); Self::serve( VHostBindListener::new(interfaces, port, requirements), target, @@ -1738,10 +1832,38 @@ impl PlainHttpProxy { ) } + fn requirements(target: &ProxyTarget) -> VHostBindRequirements { + let (public_gateways, private_ips) = + VHostTarget::::bind_requirements(target); + VHostBindRequirements { + public_gateways, + private_ips, + } + } + + /// Swaps in a target that routes like the current one, cancelling the + /// streams it does not accept. Any other target is refused. + pub fn retarget(&self, next: &ProxyTarget) -> bool { + if !self.target.peek(|target| target.same_route(next)) { + return false; + } + self.target.replace(next.clone()); + self.requirements.send(Self::requirements(next)); + let admits = next.clone(); + self.ctx + .registry + .readmit(Arc::new(move |at| admits.accepts_arrival(at))); + true + } + fn serve(mut listener: VHostBindListener, target: ProxyTarget, max_connections: usize) -> Self { let ctx = ProxyContext::new(max_connections); - let cancel = ctx.cancel.clone(); + let requirements = listener.bind_reqs.clone(); + let target = Arc::new(SyncRwLock::new(target)); + let current = target.clone(); + let accepting = ctx.clone(); let thread = tokio::spawn(async move { + let ctx = accepting; loop { let accepted = futures::future::poll_fn(|cx| listener.poll_accept(cx)).await; let (metadata, stream) = match accepted { @@ -1751,11 +1873,14 @@ impl PlainHttpProxy { continue; } }; - if !VHostTarget::::filter(&target, &metadata) { + let Some(target) = current.peek(|target| { + VHostTarget::::filter(target, &metadata) + .then(|| target.clone()) + }) else { continue; - } - let target = target.clone(); - let (stream, registration, conn_cancel) = ctx.track_with(stream); + }; + let (stream, registration, conn_cancel) = + ctx.track_with(stream, arrival::(&metadata)); tokio::spawn(async move { let _registration = registration; let work = async { @@ -1781,7 +1906,9 @@ impl PlainHttpProxy { } }); Self { - cancel, + target, + requirements, + ctx, _thread: thread.into(), } } @@ -1789,7 +1916,7 @@ impl PlainHttpProxy { impl Drop for PlainHttpProxy { fn drop(&mut self) { - self.cancel.cancel(); + self.ctx.cancel.cancel(); } } @@ -2269,6 +2396,50 @@ impl VHostServer { )) } } + /// Keeps the streams the new target admits when it routes like a solely + /// owned entry; otherwise drops the owner, then adds the new target. + fn replace( + &self, + hostname: Option, + prev: &DynVHostTarget, + owner: Arc<()>, + next: DynVHostTarget, + max_proxy_conns_per_target: usize, + ) -> Result, Error> { + if prev == &next { + return Ok(owner); + } + let moved = self.mapping.watcher_count() > 1 + && Arc::strong_count(&owner) == 1 + && prev.0.routes_like(&*next.0) + && self.mapping.send_if_modified(|writable| { + let Some(targets) = writable.get_mut(&hostname) else { + return false; + }; + let owned = targets + .get(prev) + .is_some_and(|entry| Weak::ptr_eq(&entry.rc, &Arc::downgrade(&owner))); + if !owned || targets.contains_key(&next) { + return false; + } + let Some(entry) = targets.remove(prev) else { + return false; + }; + let admits = next.clone(); + entry + .ctx + .registry + .readmit(Arc::new(move |at| admits.0.admits(at))); + targets.insert(next.clone(), entry); + self.update_bind_reqs(writable); + true + }); + if moved { + return Ok(owner); + } + drop(owner); + self.add(hostname, next, max_proxy_conns_per_target) + } fn gc(&self, hostname: Option) { self.mapping.send_if_modified(|writable| { let mut targets = writable.remove(&hostname).unwrap_or_default(); @@ -2823,6 +2994,7 @@ mod accept_filter_tests { #[cfg(test)] mod conn_cap_tests { + use std::net::Ipv4Addr; use std::time::Duration; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -2834,11 +3006,11 @@ mod conn_cap_tests { let registry = ConnRegistry::new(2); let cancel1 = CancellationToken::new(); - let _h1 = registry.register(Arc::new(AtomicU64::new(100)), cancel1.clone()); + let _h1 = registry.register(Arc::new(AtomicU64::new(100)), cancel1.clone(), None); let cancel2 = CancellationToken::new(); - let _h2 = registry.register(Arc::new(AtomicU64::new(200)), cancel2.clone()); + let _h2 = registry.register(Arc::new(AtomicU64::new(200)), cancel2.clone(), None); let cancel3 = CancellationToken::new(); - let _h3 = registry.register(Arc::new(AtomicU64::new(300)), cancel3.clone()); + let _h3 = registry.register(Arc::new(AtomicU64::new(300)), cancel3.clone(), None); assert!(cancel1.is_cancelled()); assert!(!cancel2.is_cancelled()); @@ -2853,11 +3025,12 @@ mod conn_cap_tests { let _stale = registry.register( Arc::new(AtomicU64::new(monotonic_millis())), stale_cancel.clone(), + None, ); let busy_active = Arc::new(AtomicU64::new(monotonic_millis())); let busy_cancel = CancellationToken::new(); - let _busy = registry.register(busy_active.clone(), busy_cancel.clone()); + let _busy = registry.register(busy_active.clone(), busy_cancel.clone(), None); let (a, mut b) = tokio::io::duplex(64); let mut wrapped = ActivityStream::new(a, busy_active.clone()); @@ -2870,6 +3043,7 @@ mod conn_cap_tests { let _new = registry.register( Arc::new(AtomicU64::new(monotonic_millis())), new_cancel.clone(), + None, ); assert!(stale_cancel.is_cancelled()); @@ -2883,12 +3057,48 @@ mod conn_cap_tests { let _h = registry.register( Arc::new(AtomicU64::new(monotonic_millis())), CancellationToken::new(), + None, ); assert_eq!(registry.len(), 1); } assert_eq!(registry.len(), 0); } + #[tokio::test] + async fn readmission_cancels_rejected_streams_including_later_ones() { + let registry = ConnRegistry::new(8); + let arrival = |dst: [u8; 4]| Arrival { + gateway: "eth0".parse().unwrap(), + subnets: OrdSet::new(), + src: Ipv4Addr::new(192, 168, 1, 9).into(), + dst: Ipv4Addr::from(dst).into(), + }; + let track = |arrival: Option| { + let cancel = CancellationToken::new(); + let handle = registry.register( + Arc::new(AtomicU64::new(monotonic_millis())), + cancel.clone(), + arrival, + ); + (cancel, handle) + }; + let (earlier_kept, _h1) = track(Some(arrival([192, 168, 1, 2]))); + let (earlier_dropped, _h2) = track(Some(arrival([10, 0, 0, 2]))); + + let kept: IpAddr = Ipv4Addr::new(192, 168, 1, 2).into(); + registry.readmit(Arc::new(move |at| at.dst == kept)); + assert!(!earlier_kept.is_cancelled()); + assert!(earlier_dropped.is_cancelled()); + + let (later_kept, _h3) = track(Some(arrival([192, 168, 1, 2]))); + let (later_dropped, _h4) = track(Some(arrival([10, 0, 0, 2]))); + let (unknown, _h5) = track(None); + assert!(!later_kept.is_cancelled()); + assert!(later_dropped.is_cancelled()); + assert!(unknown.is_cancelled()); + assert_eq!(registry.len(), 2); + } + #[tokio::test] async fn target_cancel_wakes_idle_proxy_task() { let ctx = ProxyContext::new(MAX_PROXY_CONNS_PER_TARGET); @@ -3264,7 +3474,7 @@ mod upstream_alpn_tests { } #[tokio::test] - async fn disabling_an_address_disconnects_its_stream_and_gates_new_arrivals() { + async fn disabling_an_address_disconnects_only_its_streams_and_gates_new_arrivals() { tokio::time::timeout(Duration::from_secs(10), async { let backend = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap(); let backend_addr = backend.local_addr().unwrap(); @@ -3341,41 +3551,51 @@ mod upstream_alpn_tests { let owner = server .add(None, DynVHostTarget::new(before.clone()), 4) .unwrap(); - let connector = - TlsConnector::from(Arc::new(client_config_no_verify(provider()).unwrap())); - let name = ServerName::IpAddress(Ipv4Addr::LOCALHOST.into()); - let mut established = connector - .connect(name.clone(), TcpStream::connect(old_addr).await.unwrap()) - .await - .unwrap(); - established.write_all(b"a").await.unwrap(); - established.flush().await.unwrap(); - let mut byte = [0]; - established.read_exact(&mut byte).await.unwrap(); - assert_eq!(&byte, b"a"); - let mut after = before; + let mut disabled = dial(old_addr).await.unwrap(); + let mut kept = dial(new_addr).await.unwrap(); + assert!(echoes(&mut disabled, b'a').await); + assert!(echoes(&mut kept, b'b').await); + let mut after = before.clone(); after.private = BTreeSet::from([new_addr.ip()]); - drop(owner); - let _replacement_owner = server.add(None, DynVHostTarget::new(after), 4).unwrap(); + let _owner = server + .replace( + None, + &DynVHostTarget::new(before), + owner, + DynVHostTarget::new(after), + 4, + ) + .unwrap(); assert!( - established.read_exact(&mut byte).await.is_err(), - "disabling an address ends the established stream" + !echoes(&mut disabled, b'c').await, + "disabling an address ends its established stream" ); - let refused = TcpStream::connect(old_addr) - .await - .expect("the old address remains bound"); - assert!(connector.connect(name.clone(), refused).await.is_err()); - let mut fresh = connector - .connect(name, TcpStream::connect(new_addr).await.unwrap()) - .await - .unwrap(); - fresh.write_all(b"c").await.unwrap(); - fresh.flush().await.unwrap(); - fresh.read_exact(&mut byte).await.unwrap(); - assert_eq!(&byte, b"c"); + assert!( + echoes(&mut kept, b'd').await, + "a stream on a still-enabled address survives" + ); + assert!(dial(old_addr).await.is_err()); + assert!(echoes(&mut dial(new_addr).await.unwrap(), b'e').await); }) .await - .expect("address disable disconnects the stream and gates arrivals within 10s"); + .expect("address disable disconnects its stream and gates arrivals within 10s"); + } + + async fn dial(addr: SocketAddr) -> std::io::Result> { + let tcp = TcpStream::connect(addr) + .await + .expect("the address remains bound"); + TlsConnector::from(Arc::new(client_config_no_verify(provider()).unwrap())) + .connect(ServerName::IpAddress(Ipv4Addr::LOCALHOST.into()), tcp) + .await + } + + async fn echoes(stream: &mut (impl AsyncRead + AsyncWrite + Unpin), byte: u8) -> bool { + let mut echoed = [0]; + stream.write_all(&[byte]).await.is_ok() + && stream.flush().await.is_ok() + && stream.read_exact(&mut echoed).await.is_ok() + && echoed == [byte] } #[tokio::test] diff --git a/shared-libs/crates/start-core/src/net/vhost/plain_http_tests.rs b/shared-libs/crates/start-core/src/net/vhost/plain_http_tests.rs index 6615d0f5b0..b69c9f578e 100644 --- a/shared-libs/crates/start-core/src/net/vhost/plain_http_tests.rs +++ b/shared-libs/crates/start-core/src/net/vhost/plain_http_tests.rs @@ -280,6 +280,50 @@ async fn dropping_a_plaintext_proxy_cancels_existing_streams_and_releases_its_li .unwrap(); } +#[tokio::test] +async fn retargeting_a_plaintext_proxy_keeps_only_the_streams_it_still_accepts() { + tokio::time::timeout(Duration::from_secs(10), async { + let (upstream, mut requests, _backend) = backend().await; + let (addr, server) = proxy( + "127.0.0.1".parse().unwrap(), + upstream, + ProxyOptions::Http { + add_x_forwarded_headers: false, + auth: None, + }, + 4, + ) + .await; + let (mut client, _connection) = client(addr).await; + assert_eq!( + client.send_request(request(None)).await.unwrap().status(), + StatusCode::OK + ); + requests.recv().await.unwrap(); + + let mut widened = server.target.read(); + widened.private.insert("127.0.0.3".parse().unwrap()); + assert!(server.retarget(&widened)); + assert_eq!( + client.send_request(request(None)).await.unwrap().status(), + StatusCode::OK, + "a stream the new target accepts survives" + ); + requests.recv().await.unwrap(); + + let mut rerouted = widened.clone(); + rerouted.addr = "127.0.0.1:1".parse().unwrap(); + assert!(!server.retarget(&rerouted)); + + let mut narrowed = widened; + narrowed.private.remove(&addr.ip()); + assert!(server.retarget(&narrowed)); + assert!(client.send_request(request(None)).await.is_err()); + }) + .await + .unwrap(); +} + #[tokio::test] async fn plaintext_connection_cap_evicts_an_idle_connection() { tokio::time::timeout(Duration::from_secs(10), async { From f09a25521fc6a0fe059e8f65e775d5642a49e8c4 Mon Sep 17 00:00:00 2001 From: Helix the Red <355572797+helix-red@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:05:36 -0700 Subject: [PATCH 05/38] fix(gateway): honor WireGuard MTU on gateway import and update (#4791) * fix(gateway): honor WireGuard MTU on gateway import and update WgConfig dropped `MTU =` from [Interface], so imported gateways ran at NetworkManager's automatic MTU (the kernel's 1420). Parse and validate it, and emit `wireguard.mtu` in the NM settings used by both add and update. NetworkManager 1.52 refuses a Device.Reapply that changes `wireguard.mtu` (nm-device-wireguard.c can_reapply_change), so the update path reapplies with the applied connection's MTU and sets the new link MTU directly; Update2 still persists the new value for the next activation. Closes #4786 Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(gateway): reactivate WireGuard gateways whose MTU changes NetworkManager rejects a Reapply that changes wireguard.mtu, and its deferred post-Reapply MTU commit restores the applied MTU, so a direct link write could be reverted and an applied MTU that never changed made later comparisons stale. An update that changes the MTU now reactivates the connection: NM restores the original link MTU on deactivation and applies the saved profile's MTU on activation. Other updates still Reapply in place. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(gateway): wait for WireGuard reactivation to complete Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol --------- Co-authored-by: helix-white <267227783+helix-a@users.noreply.github.com> --- .../patch-fixed-wireguard-gateway-mtu.md | 5 + .../crates/start-core/src/net/gateway.rs | 142 +++++++++++++++++- .../crates/start-core/src/net/tunnel.rs | 8 +- 3 files changed, 144 insertions(+), 11 deletions(-) create mode 100644 projects/start-os/changelog/patch-fixed-wireguard-gateway-mtu.md diff --git a/projects/start-os/changelog/patch-fixed-wireguard-gateway-mtu.md b/projects/start-os/changelog/patch-fixed-wireguard-gateway-mtu.md new file mode 100644 index 0000000000..eb0a187c55 --- /dev/null +++ b/projects/start-os/changelog/patch-fixed-wireguard-gateway-mtu.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- WireGuard gateways now honor the `MTU` setting in their configuration, both when added and when their configuration is updated. Configurations without it still use the automatic MTU. Updating a gateway's configuration to a different MTU briefly reconnects it. diff --git a/shared-libs/crates/start-core/src/net/gateway.rs b/shared-libs/crates/start-core/src/net/gateway.rs index 2e0962a208..8d071a2f2f 100644 --- a/shared-libs/crates/start-core/src/net/gateway.rs +++ b/shared-libs/crates/start-core/src/net/gateway.rs @@ -248,6 +248,8 @@ pub(crate) async fn wireguard_psk(interface: &str) -> Result, E /// Update2 flag: persist the change to disk (NM_SETTINGS_UPDATE2_FLAG_TO_DISK). const NM_UPDATE2_TO_DISK: u32 = 0x1; const WG_DNS_PRIORITY: i32 = 10; +const IPV4_MIN_MTU: u32 = 68; +const IPV6_MIN_MTU: u32 = 1280; fn endpoint_domain(endpoint: &str) -> Option { let (host, port) = endpoint.rsplit_once(':')?; @@ -274,6 +276,17 @@ pub(crate) fn wireguard_config_domains(config: &str) -> Result>, +) -> Result, Error> { + let Some(mtu) = settings.get("wireguard").and_then(|wg| wg.get("mtu")) else { + return Ok(None); + }; + let mtu = mtu.downcast_ref::().with_kind(ErrorKind::Network)?; + Ok((mtu != 0).then_some(mtu)) +} + fn settings_endpoint_domains( settings: &HashMap>, ) -> Result, Error> { @@ -307,6 +320,8 @@ struct WgConfig { addresses: Vec<(IpAddr, u8)>, dns: Vec, listen_port: Option, + /// None selects NetworkManager's automatic MTU. + mtu: Option, peers: Vec, } @@ -328,6 +343,7 @@ impl WgConfig { let mut addresses = Vec::new(); let mut dns = Vec::new(); let mut listen_port = None; + let mut mtu = None; let mut peers: Vec = Vec::new(); for raw in config.lines() { @@ -383,6 +399,15 @@ impl WgConfig { } } "listenport" => listen_port = val.parse().ok(), + "mtu" => { + mtu = Some( + val.parse::() + .ok() + .map(u32::from) + .filter(|mtu| *mtu >= IPV4_MIN_MTU) + .ok_or_else(|| invalid("MTU"))?, + ) + } _ => {} }, Section::Peer => { @@ -400,11 +425,17 @@ impl WgConfig { } } + if mtu.is_some_and(|mtu| mtu < IPV6_MIN_MTU) && addresses.iter().any(|(ip, _)| ip.is_ipv6()) + { + return Err(invalid("MTU below 1280 with an IPv6 address")); + } + Ok(Self { private_key: private_key.ok_or_else(|| invalid("missing PrivateKey"))?, addresses, dns, listen_port, + mtu, peers, }) } @@ -437,6 +468,9 @@ impl WgConfig { if let Some(port) = self.listen_port { wg.insert("listen-port".into(), ov(port.into())?); } + if let Some(mtu) = self.mtu { + wg.insert("mtu".into(), ov(mtu.into())?); + } let peers: Vec> = self .peers .iter() @@ -523,13 +557,19 @@ impl WgConfig { Ok(settings) } + + /// NetworkManager cannot Reapply a WireGuard MTU change. + fn needs_reactivation( + &self, + applied: &HashMap>, + ) -> Result { + Ok(settings_wireguard_mtu(applied)? != self.mtu) + } } -/// Apply a re-issued WireGuard config to `interface`'s existing NM connection in -/// place via D-Bus Update2 + Device.Reapply. The wg device is never deleted, so -/// the tunnel — and the request that triggered the update, when it rides this -/// same tunnel — is not torn down. Reapply applies the change to the live device -/// without bringing the interface down (NM supports this for WireGuard). +/// Replaces the saved profile and applies it to the live gateway. +/// MTU changes reconnect the gateway and wait for activation to finish. +/// Other changes preserve the active connection. pub(crate) async fn update_wireguard_config(interface: &str, config: &str) -> Result<(), Error> { let parsed = WgConfig::parse(config)?; @@ -575,6 +615,19 @@ pub(crate) async fn update_wireguard_config(interface: &str, config: &str) -> Re HashMap::new(), ) .await?; + let (applied, _) = device_proxy.get_applied_connection(0).await?; + if parsed.needs_reactivation(&applied)? { + Command::new("nmcli") + .arg("connection") + .arg("up") + .arg("uuid") + .arg(&uuid) + .arg("ifname") + .arg(interface) + .invoke(ErrorKind::Network) + .await?; + return Ok(()); + } // Full settings so Reapply doesn't strip the connection's other peer fields. device_proxy .reapply(parsed.to_nm_settings(interface, Some(uuid.as_str()))?, 0, 0) @@ -1403,6 +1456,12 @@ mod device { flags: u32, ) -> Result<(), Error>; + /// The settings the device is running with, and their version id. + fn get_applied_connection( + &self, + flags: u32, + ) -> Result<(HashMap>, u64), Error>; + #[zbus(property)] fn ip_interface(&self) -> Result; @@ -4492,6 +4551,79 @@ mod wg_config_tests { assert!(WgConfig::parse("[Interface]\nPrivateKey = k=\nAddress = fd00::2/200\n").is_err()); } + #[test] + fn explicit_mtu_reaches_nm_settings() { + let config = + "[Interface]\nPrivateKey = k=\nAddress = 10.0.0.2/24, fd00::2/64\nMTU = 1320\n"; + let parsed = WgConfig::parse(config).unwrap(); + assert_eq!(parsed.mtu, Some(1320)); + let settings = parsed.to_nm_settings("wg0", None).unwrap(); + assert_eq!( + settings["wireguard"]["mtu"].downcast_ref::().unwrap(), + 1320 + ); + assert_eq!(settings_wireguard_mtu(&settings).unwrap(), Some(1320)); + } + + #[test] + fn missing_mtu_stays_automatic() { + let parsed = + WgConfig::parse("[Interface]\nPrivateKey = k=\nAddress = 10.0.0.2/24\n").unwrap(); + assert_eq!(parsed.mtu, None); + let settings = parsed.to_nm_settings("wg0", None).unwrap(); + assert!(!settings["wireguard"].contains_key("mtu")); + assert_eq!(settings_wireguard_mtu(&settings).unwrap(), None); + + let auto = HashMap::from([( + "wireguard".to_string(), + HashMap::from([("mtu".to_string(), OwnedValue::from(0u32))]), + )]); + assert_eq!(settings_wireguard_mtu(&auto).unwrap(), None); + } + + #[test] + fn mtu_changes_reactivate_and_other_updates_reapply() { + let config = |mtu: &str| { + WgConfig::parse(&format!( + "[Interface]\nPrivateKey = k=\nAddress = 10.0.0.2/24\n{mtu}" + )) + .unwrap() + }; + let auto = config(""); + let explicit = config("MTU = 1320\n"); + let applied_auto = auto.to_nm_settings("wg0", None).unwrap(); + let applied_explicit = explicit.to_nm_settings("wg0", None).unwrap(); + + assert!(!auto.needs_reactivation(&applied_auto).unwrap()); + assert!(explicit.needs_reactivation(&applied_auto).unwrap()); + assert!(!explicit.needs_reactivation(&applied_explicit).unwrap()); + assert!( + config("MTU = 1400\n") + .needs_reactivation(&applied_explicit) + .unwrap() + ); + assert!(auto.needs_reactivation(&applied_explicit).unwrap()); + } + + #[test] + fn rejects_invalid_mtu() { + for mtu in ["abc", "0", "67", "65536", "-1"] { + let config = + format!("[Interface]\nPrivateKey = k=\nAddress = 10.0.0.2/24\nMTU = {mtu}\n"); + assert!(WgConfig::parse(&config).is_err(), "MTU = {mtu}"); + } + assert!( + WgConfig::parse("[Interface]\nPrivateKey = k=\nAddress = 10.0.0.2/24\nMTU = 1200\n") + .is_ok() + ); + assert!( + WgConfig::parse( + "[Interface]\nPrivateKey = k=\nAddress = 10.0.0.2/24, fd00::2/64\nMTU = 1200\n" + ) + .is_err() + ); + } + // add() lets NM generate the uuid; update() preserves the existing one so the // same profile is replaced in place rather than redefined. #[test] diff --git a/shared-libs/crates/start-core/src/net/tunnel.rs b/shared-libs/crates/start-core/src/net/tunnel.rs index c8675b7964..71ef9b0bc3 100644 --- a/shared-libs/crates/start-core/src/net/tunnel.rs +++ b/shared-libs/crates/start-core/src/net/tunnel.rs @@ -369,11 +369,8 @@ pub struct UpdateTunnelParams { rpc_toolkit::reflect_ts!(UpdateTunnelParams); rpc_toolkit::ts_export!(UpdateTunnelParams, namespaces = [""]); -/// Replace the WireGuard config behind an existing gateway interface in place, -/// keeping the gateway id and everything keyed to it (forwards, private/public -/// domains). Used to re-issue a config — e.g. one that now carries a `DNS =` -/// line. Applied via D-Bus Update2 + Device.Reapply, so the wg device is never -/// torn down and the gateway (and the request riding its tunnel) survives. +/// Preserves the gateway id, port forwards, and domains across config updates. +/// MTU changes reconnect the gateway; other changes keep its connection active. pub async fn update_tunnel( ctx: RpcContext, UpdateTunnelParams { id, config }: UpdateTunnelParams, @@ -402,7 +399,6 @@ pub async fn update_tunnel( )); } - // Reapply keeps the device carrying this RPC alive. crate::net::gateway::update_wireguard_config(id.as_str(), &config).await } From 9d9699c07e558336c9b82a45738d04eef44b5aaa Mon Sep 17 00:00:00 2001 From: "start9-docs-bot[bot]" <315476469+start9-docs-bot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:19:50 +0000 Subject: [PATCH 06/38] docs: backport live-docs a5f53c571 to master Backports the following from live-docs: - a5f53c571 docs(sdk): gate the dependent-admission examples with proxy.auth (#4797) --- projects/start-sdk/docs/src/interfaces.md | 4 ++-- .../start-sdk/docs/src/recipe-dependent-auth.md | 2 +- projects/start-sdk/docs/src/recipes.md | 14 +++++++------- projects/start-sdk/docs/src/service-to-service.md | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/projects/start-sdk/docs/src/interfaces.md b/projects/start-sdk/docs/src/interfaces.md index afc966b578..6237df826f 100644 --- a/projects/start-sdk/docs/src/interfaces.md +++ b/projects/start-sdk/docs/src/interfaces.md @@ -752,7 +752,7 @@ const userTokens = (await storeJson.read(s => s.apiKeys).const(effects)) ?? [] await sdk.MultiHost.of(effects, apiHostId).bindPort(apiPort, { protocol: 'http', - addSsl: { + proxy: { auth: { type: 'bearer', tokens: [...(apiKey ? [apiKey] : []), ...userTokens.map(k => k.token)], @@ -768,7 +768,7 @@ await sdk.MultiHost.of(effects, apiHostId).bindPort(apiPort, { if (apiKey) { const apiOrigin = await sdk.MultiHost.of(effects, apiKeyHostId).bindPort(apiPort, { protocol: 'http', - addSsl: { auth: { type: 'bearer', tokens: [apiKey], realm: null } }, + proxy: { auth: { type: 'bearer', tokens: [apiKey], realm: null } }, }) receipts.push(await apiOrigin.export([api])) // `type: 'api'` } diff --git a/projects/start-sdk/docs/src/recipe-dependent-auth.md b/projects/start-sdk/docs/src/recipe-dependent-auth.md index 94622ce036..b1a72801db 100644 --- a/projects/start-sdk/docs/src/recipe-dependent-auth.md +++ b/projects/start-sdk/docs/src/recipe-dependent-auth.md @@ -1,6 +1,6 @@ # Let Dependents Through a Proxy Auth Gate -A binding gated with `addSsl.auth` challenges every client on every address, the plaintext bridge address included. A service that depends on it gets `401` unless it sends a credential the gate accepts. Both sides of the dependency take part: the gated service publishes a machine key, and its dependents read it and send it. +A binding gated with `proxy.auth` challenges every client on every address, the plaintext bridge address included. A service that depends on it gets `401` unless it sends a credential the gate accepts. Both sides of the dependency take part: the gated service publishes a machine key, and its dependents read it and send it. ## Solution diff --git a/projects/start-sdk/docs/src/recipes.md b/projects/start-sdk/docs/src/recipes.md index d3b9c3d65d..20582c7f8c 100644 --- a/projects/start-sdk/docs/src/recipes.md +++ b/projects/start-sdk/docs/src/recipes.md @@ -62,13 +62,13 @@ If you're using [Claude Code](https://claude.com/claude-code) (recommended), poi ## Dependencies -| Recipe | Description | -| -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| [Depend on Another Service](recipe-dependency.md) | Declare a dependency, read its connection info, and auto-configure | -| [Enforce Settings on a Dependency](recipe-enforce-dependency.md) | Create a cross-service task that requires specific dependency configuration | -| [Mount Volumes from Another Service](recipe-mount-dependency.md) | Read-only access to a dependency's data volume | -| [Let Dependents Through a Proxy Auth Gate](recipe-dependent-auth.md) | Publish a key on a `public` volume so dependents pass an `addSsl.auth` gate, and read it on the other side | -| [Support Alternative Dependencies](recipe-alternative-deps.md) | Let users choose between backends (e.g., LND vs CLN) | +| Recipe | Description | +| -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| [Depend on Another Service](recipe-dependency.md) | Declare a dependency, read its connection info, and auto-configure | +| [Enforce Settings on a Dependency](recipe-enforce-dependency.md) | Create a cross-service task that requires specific dependency configuration | +| [Mount Volumes from Another Service](recipe-mount-dependency.md) | Read-only access to a dependency's data volume | +| [Let Dependents Through a Proxy Auth Gate](recipe-dependent-auth.md) | Publish a key on a `public` volume so dependents pass a `proxy.auth` gate, and read it on the other side | +| [Support Alternative Dependencies](recipe-alternative-deps.md) | Let users choose between backends (e.g., LND vs CLN) | ## Data & Health diff --git a/projects/start-sdk/docs/src/service-to-service.md b/projects/start-sdk/docs/src/service-to-service.md index 12c4506ac9..1c3a2c4ad7 100644 --- a/projects/start-sdk/docs/src/service-to-service.md +++ b/projects/start-sdk/docs/src/service-to-service.md @@ -67,7 +67,7 @@ When a dependency [retires](interfaces.md#retiring-a-host-or-binding) the host o ### Reaching a gated dependency -A binding with [`addSsl.auth`](interfaces.md#authenticating-at-the-proxy) challenges its bridge address like any other, so dialing it without a credential gets `401`. A dependency that [admits dependents](interfaces.md#admitting-dependent-services) publishes a key at `credentials.json` → `apiKey` on its `public` volume and exports the id of the host that accepts it. Resolve **that** host, not the browser one: +A binding with [`proxy.auth`](interfaces.md#authenticating-at-the-proxy) challenges its bridge address like any other, so dialing it without a credential gets `401`. A dependency that [admits dependents](interfaces.md#admitting-dependent-services) publishes a key at `credentials.json` → `apiKey` on its `public` volume and exports the id of the host that accepts it. Resolve **that** host, not the browser one: ```typescript import { apiKeyHostId, apiPort } from 'llama-cpp-startos/startos/utils' From d8e0074377cba75ba82feb794ab8567c84ea6ec8 Mon Sep 17 00:00:00 2001 From: Matt Hill <9935159+MattDHill@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:58:12 -0700 Subject: [PATCH 07/38] fix(tunnel): validate subnet and device names (#4798) * fix(tunnel): validate subnet and device names Device names are rendered into the first comment line of each generated WireGuard client config, so a name containing a line break could add arbitrary lines to that config. Reject blank names, names with any control character, and names longer than 64 characters in add-subnet and add-device (which also handles renames), matching StartWRT's peer-name rules. Co-Authored-By: Claude Opus 5.5 * fix(tunnel): localize name-validation errors Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../changelog/patch-security-device-names.md | 5 +++ .../crates/start-core/locales/i18n.yaml | 7 ++++ .../crates/start-core/src/tunnel/api.rs | 41 +++++++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 projects/start-tunnel/changelog/patch-security-device-names.md diff --git a/projects/start-tunnel/changelog/patch-security-device-names.md b/projects/start-tunnel/changelog/patch-security-device-names.md new file mode 100644 index 0000000000..ed719eb3d9 --- /dev/null +++ b/projects/start-tunnel/changelog/patch-security-device-names.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Subnet and device names must be 1–64 characters with no control characters. diff --git a/shared-libs/crates/start-core/locales/i18n.yaml b/shared-libs/crates/start-core/locales/i18n.yaml index 5ef0dca066..08fa3ad088 100644 --- a/shared-libs/crates/start-core/locales/i18n.yaml +++ b/shared-libs/crates/start-core/locales/i18n.yaml @@ -4265,6 +4265,13 @@ tunnel.api.invalid-endpoint: fr_FR: 'Saisissez une adresse IPv4, IPv6 ou un nom DNS sans schéma, port ni chemin' pl_PL: 'Wprowadź adres IPv4, IPv6 lub nazwę DNS bez schematu, portu ani ścieżki' +tunnel.api.invalid-name: + en_US: 'Names must not be empty or only whitespace, must contain no control characters, and must be at most %{max} characters long' + de_DE: 'Namen dürfen nicht leer sein oder nur aus Leerzeichen bestehen, keine Steuerzeichen enthalten und höchstens %{max} Zeichen lang sein' + es_ES: 'Los nombres no pueden estar vacíos ni contener solo espacios, no deben contener caracteres de control y deben tener como máximo %{max} caracteres' + fr_FR: 'Les noms ne doivent pas être vides ni composés uniquement d’espaces, ne doivent contenir aucun caractère de contrôle et doivent comporter au maximum %{max} caractères' + pl_PL: 'Nazwy nie mogą być puste ani składać się wyłącznie z białych znaków, nie mogą zawierać znaków sterujących i mogą mieć najwyżej %{max} znaków' + util.crypto.invalid-backup-key: en_US: "The wrapped backup key is invalid or could not be authenticated." de_DE: "Der verschlüsselte Sicherungsschlüssel ist ungültig oder konnte nicht authentifiziert werden." diff --git a/shared-libs/crates/start-core/src/tunnel/api.rs b/shared-libs/crates/start-core/src/tunnel/api.rs index bb2894d264..ff528ef4e2 100644 --- a/shared-libs/crates/start-core/src/tunnel/api.rs +++ b/shared-libs/crates/start-core/src/tunnel/api.rs @@ -599,11 +599,28 @@ pub struct AddSubnetParams { rpc_toolkit::reflect_ts!(AddSubnetParams); rpc_toolkit::ts_export!(AddSubnetParams, namespaces = ["tunnel"]); +const MAX_NAME_LEN: usize = 64; + +/// A device name becomes a comment line in its WireGuard config. +fn validate_name(name: &str) -> Result<(), Error> { + if name.trim().is_empty() + || name.chars().any(char::is_control) + || name.chars().count() > MAX_NAME_LEN + { + return Err(Error::new( + eyre!(t!("tunnel.api.invalid-name", max = MAX_NAME_LEN)), + ErrorKind::InvalidRequest, + )); + } + Ok(()) +} + pub async fn add_subnet( ctx: TunnelContext, AddSubnetParams { name }: AddSubnetParams, SubnetParams { mut subnet }: SubnetParams, ) -> Result<(), Error> { + validate_name(&name)?; if subnet.prefix_len() > 24 { return Err(Error::new( eyre!("invalid subnet"), @@ -1009,6 +1026,7 @@ pub async fn add_device( kind, }: AddDeviceParams, ) -> Result<(), Error> { + validate_name(&name)?; let server = ctx .db .mutate(|db| { @@ -1998,6 +2016,29 @@ pub async fn list_http_redirects(ctx: TunnelContext) -> Result, subnet_wan: Option<&str>, From ae67559f37378c9934f20aaceb3b60990b7e5cca Mon Sep 17 00:00:00 2001 From: Helix the Red <355572797+helix-red@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:09:37 -0700 Subject: [PATCH 08/38] feat(ci): read package workflow registry settings from caller variables; add optional registry proxy (#4801) * feat(ci): route package publishing registry requests through an optional proxy Adds a REGISTRY_PROXY input to the reusable release and tagAndRelease workflows. When set, the configure-registry-proxy action writes it as start-cli's proxy, so registries can be .onion addresses; a loopback proxy with nothing listening gets a Tor daemon started on the runner. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * feat(ci): default REGISTRY_PROXY to the caller's variable Reusable workflows evaluate vars against the caller's repository, so package repos pick up an org or repo REGISTRY_PROXY variable without passing it from their workflow files. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * feat(ci): default every registry input to the caller's variable REFERENCE_REGISTRY, RELEASE_REGISTRY and S3_S9PKS_BASE_URL now default to the calling repository's variables like REGISTRY_PROXY, so package callers pass only secrets. A missing reference registry fails with a named error instead of an empty-registry query. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(ci): keep one proxy setting in a shared start-cli config Forgejo's host backend runs Tag and Publish with the same HOME, so appending a proxy line twice left a duplicate key that start-cli rejects. Replace any existing proxy line instead, and clear it when no proxy is configured so a persistent runner does not inherit a stale one. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * feat(ci): start Tor only when the repository opts in with REGISTRY_TOR A loopback REGISTRY_PROXY no longer starts a Tor daemon implicitly. REGISTRY_TOR=true starts Tor on the publishing runners and proxies through it; REGISTRY_PROXY uses an existing proxy as given. Setting both is an error. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * feat(ci): never start Tor on the runner; REGISTRY_PROXY must name a reachable proxy The workflows only point start-cli at the configured proxy. Running a Tor SOCKS proxy the runners can reach is the repository owner's job. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --- .forgejo/workflows/release.yml | 14 +++- .forgejo/workflows/tagAndRelease.yml | 23 +++++- .../configure-registry-proxy/action.yml | 41 ++++++++++ .../tests/configure-registry-proxy.test.mjs | 75 +++++++++++++++++++ .github/workflows/release.yml | 15 +++- .github/workflows/tagAndRelease.yml | 24 +++++- .../.forgejo/workflows/release.yml | 3 - .../.forgejo/workflows/tagAndRelease.yml | 4 - .../.github/workflows/release.yml | 3 - .../.github/workflows/tagAndRelease.yml | 4 - .../start-sdk/docs/src/project-structure.md | 11 +-- 11 files changed, 184 insertions(+), 33 deletions(-) create mode 100644 .github/actions/configure-registry-proxy/action.yml create mode 100644 .github/actions/tests/configure-registry-proxy.test.mjs diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index 5f95a88d8d..9164ea76b8 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -12,11 +12,17 @@ name: Release type: boolean default: false RELEASE_REGISTRY: - description: The registry to publish to + description: The registry to publish to. Defaults to the caller's RELEASE_REGISTRY variable. type: string + default: ${{ vars.RELEASE_REGISTRY }} S3_S9PKS_BASE_URL: - description: S3 base URL for package uploads (e.g. https://bucket.region.digitaloceanspaces.com) + description: S3 base URL for package uploads (e.g. https://bucket.region.digitaloceanspaces.com). Defaults to the caller's S3_S9PKS_BASE_URL variable. type: string + default: ${{ vars.S3_S9PKS_BASE_URL }} + REGISTRY_PROXY: + description: Proxy URL start-cli uses to reach the registries, e.g. socks5h://proxy.example:9050 for .onion registries. The proxy must already be reachable from the runner. Defaults to the caller's REGISTRY_PROXY variable. + type: string + default: ${{ vars.REGISTRY_PROXY }} secrets: DEV_KEY: description: Developer signing key @@ -109,6 +115,10 @@ jobs: steps: - name: Setup publish environment uses: https://github.com/Start9Labs/start-technologies/.forgejo/actions/setup-publish-env@master + - name: Configure registry proxy + uses: https://github.com/Start9Labs/start-technologies/.github/actions/configure-registry-proxy@master + with: + proxy: ${{ inputs.REGISTRY_PROXY }} - name: Checkout services repository uses: https://github.com/actions/checkout@v6 with: diff --git a/.forgejo/workflows/tagAndRelease.yml b/.forgejo/workflows/tagAndRelease.yml index 1cec470000..654f157161 100644 --- a/.forgejo/workflows/tagAndRelease.yml +++ b/.forgejo/workflows/tagAndRelease.yml @@ -4,19 +4,25 @@ name: Tag and Release workflow_call: inputs: REFERENCE_REGISTRY: - description: Registry where published versions are permanent (used to check if a version is already taken) + description: Registry where published versions are permanent (used to check if a version is already taken). Defaults to the caller's REFERENCE_REGISTRY variable. type: string - required: true + default: ${{ vars.REFERENCE_REGISTRY }} FREE_DISK_SPACE: description: Free up disk space before building type: boolean default: false RELEASE_REGISTRY: - description: Test registry to publish to + description: Test registry to publish to. Defaults to the caller's RELEASE_REGISTRY variable. type: string + default: ${{ vars.RELEASE_REGISTRY }} S3_S9PKS_BASE_URL: - description: S3 base URL for package uploads + description: S3 base URL for package uploads. Defaults to the caller's S3_S9PKS_BASE_URL variable. + type: string + default: ${{ vars.S3_S9PKS_BASE_URL }} + REGISTRY_PROXY: + description: Proxy URL start-cli uses to reach the registries, e.g. socks5h://proxy.example:9050 for .onion registries. The proxy must already be reachable from the runner. Defaults to the caller's REGISTRY_PROXY variable. type: string + default: ${{ vars.REGISTRY_PROXY }} secrets: DEV_KEY: description: Developer signing key @@ -40,6 +46,10 @@ jobs: uses: https://github.com/actions/checkout@v6 - name: Install start-cli uses: https://github.com/Start9Labs/start-technologies/.github/actions/install-start-cli@master + - name: Configure registry proxy + uses: https://github.com/Start9Labs/start-technologies/.github/actions/configure-registry-proxy@master + with: + proxy: ${{ inputs.REGISTRY_PROXY }} - name: Extract package ID and version id: extract uses: https://github.com/Start9Labs/start-technologies/.github/actions/extract-version@master @@ -49,6 +59,10 @@ jobs: PACKAGE_ID="${{ steps.extract.outputs.package_id }}" VERSION="${{ steps.extract.outputs.version }}" REFERENCE_REGISTRY="${{ inputs.REFERENCE_REGISTRY }}" + if [ -z "$REFERENCE_REGISTRY" ]; then + echo "::error::No reference registry: set the REFERENCE_REGISTRY variable or pass the input." + exit 1 + fi # hello-world is the canonical package scaffold, not a released package. # Skipping it here lets every caller (including hello-world's own) use the @@ -94,6 +108,7 @@ jobs: FREE_DISK_SPACE: ${{ inputs.FREE_DISK_SPACE }} RELEASE_REGISTRY: ${{ inputs.RELEASE_REGISTRY }} S3_S9PKS_BASE_URL: ${{ inputs.S3_S9PKS_BASE_URL }} + REGISTRY_PROXY: ${{ inputs.REGISTRY_PROXY }} secrets: DEV_KEY: ${{ secrets.DEV_KEY }} S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }} diff --git a/.github/actions/configure-registry-proxy/action.yml b/.github/actions/configure-registry-proxy/action.yml new file mode 100644 index 0000000000..73a6c0d27f --- /dev/null +++ b/.github/actions/configure-registry-proxy/action.yml @@ -0,0 +1,41 @@ +name: 'Configure Registry Proxy' +description: | + Routes this runner's start-cli requests through a proxy, so registries can be + Tor (.onion) addresses. No proxy removes any proxy an earlier job configured. +inputs: + proxy: + description: 'Proxy URL for start-cli, e.g. socks5h://proxy.example:9050. A .onion registry needs socks5h, which resolves names through the proxy.' + required: false + default: '' +runs: + using: 'composite' + steps: + - name: Configure registry proxy + env: + PROXY: ${{ inputs.proxy }} + run: | + # Host-backed Forgejo jobs share this home directory across jobs and runs. + CONFIG=~/.startos/config.yaml + without_proxy() { grep -v '^proxy:' "$CONFIG" 2>/dev/null || true; } + + if [ -z "$PROXY" ]; then + if [ -f "$CONFIG" ]; then + without_proxy > "$CONFIG.new" + mv "$CONFIG.new" "$CONFIG" + fi + exit 0 + fi + + case "$PROXY" in + *://*) ;; + *) + echo "::error::The registry proxy has no scheme; use e.g. socks5h://proxy.example:9050" + exit 1 + ;; + esac + + mkdir -p ~/.startos + { without_proxy; printf 'proxy: %s\n' "$(jq -n --arg p "$PROXY" '$p')"; } > "$CONFIG.new" + mv "$CONFIG.new" "$CONFIG" + echo "start-cli will reach registries through the configured proxy." + shell: bash diff --git a/.github/actions/tests/configure-registry-proxy.test.mjs b/.github/actions/tests/configure-registry-proxy.test.mjs new file mode 100644 index 0000000000..adc641f726 --- /dev/null +++ b/.github/actions/tests/configure-registry-proxy.test.mjs @@ -0,0 +1,75 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' + +const require = createRequire(import.meta.url) +const yaml = require('js-yaml') +const action = yaml.load( + readFileSync( + new URL('../configure-registry-proxy/action.yml', import.meta.url), + 'utf8', + ), +) +const step = action.runs.steps.find( + ({ name }) => name === 'Configure registry proxy', +) +for (const existing of [ + '', + 'registry: https://registry.example', + 'registry: https://registry.example\nproxy: "socks5h://stale.example:9050"', +]) { + test(`reapplying a proxy leaves one proxy in ${JSON.stringify(existing)}`, t => { + const home = mkdtempSync(join(tmpdir(), 'registry-proxy-test-')) + t.after(() => rmSync(home, { recursive: true, force: true })) + const config = join(home, '.startos', 'config.yaml') + if (existing) { + mkdirSync(join(home, '.startos')) + writeFileSync(config, existing) + } + const proxy = 'socks5h://registry-proxy.example:9050' + const configure = () => + execFileSync('bash', ['-e', '-o', 'pipefail', '-c', step.run], { + env: { ...process.env, HOME: home, PROXY: proxy }, + stdio: 'pipe', + }) + + configure() + const first = readFileSync(config, 'utf8') + configure() + const second = readFileSync(config, 'utf8') + + assert.equal(second, first) + assert.deepEqual(yaml.load(second), { + ...(existing ? { registry: 'https://registry.example' } : {}), + proxy, + }) + }) +} + +test('an unset proxy removes a proxy an earlier job configured', t => { + const home = mkdtempSync(join(tmpdir(), 'registry-proxy-test-')) + t.after(() => rmSync(home, { recursive: true, force: true })) + const config = join(home, '.startos', 'config.yaml') + mkdirSync(join(home, '.startos')) + writeFileSync( + config, + 'registry: https://registry.example\nproxy: "socks5h://stale.example:9050"\n', + ) + execFileSync('bash', ['-e', '-o', 'pipefail', '-c', step.run], { + env: { ...process.env, HOME: home, PROXY: '' }, + stdio: 'pipe', + }) + assert.deepEqual(yaml.load(readFileSync(config, 'utf8')), { + registry: 'https://registry.example', + }) +}) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 186f313406..6ae8232553 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,11 +12,17 @@ on: type: boolean default: false RELEASE_REGISTRY: - description: 'The registry to publish to' + description: "The registry to publish to. Defaults to the caller's RELEASE_REGISTRY variable." type: string + default: ${{ vars.RELEASE_REGISTRY }} S3_S9PKS_BASE_URL: - description: 'S3 base URL for package uploads (e.g. https://bucket.region.digitaloceanspaces.com)' + description: "S3 base URL for package uploads (e.g. https://bucket.region.digitaloceanspaces.com). Defaults to the caller's S3_S9PKS_BASE_URL variable." type: string + default: ${{ vars.S3_S9PKS_BASE_URL }} + REGISTRY_PROXY: + description: "Proxy URL start-cli uses to reach the registries, e.g. socks5h://proxy.example:9050 for .onion registries. The proxy must already be reachable from the runner. Defaults to the caller's REGISTRY_PROXY variable." + type: string + default: ${{ vars.REGISTRY_PROXY }} secrets: DEV_KEY: description: 'Developer signing key' @@ -157,6 +163,11 @@ jobs: - name: Setup publish environment uses: Start9Labs/start-technologies/.github/actions/setup-publish-env@master + - name: Configure registry proxy + uses: Start9Labs/start-technologies/.github/actions/configure-registry-proxy@master + with: + proxy: ${{ inputs.REGISTRY_PROXY }} + - name: Checkout services repository uses: actions/checkout@v6 with: diff --git a/.github/workflows/tagAndRelease.yml b/.github/workflows/tagAndRelease.yml index 238e445375..651070f12c 100644 --- a/.github/workflows/tagAndRelease.yml +++ b/.github/workflows/tagAndRelease.yml @@ -4,19 +4,25 @@ on: workflow_call: inputs: REFERENCE_REGISTRY: - description: 'Registry where published versions are permanent (used to check if a version is already taken)' + description: "Registry where published versions are permanent (used to check if a version is already taken). Defaults to the caller's REFERENCE_REGISTRY variable." type: string - required: true + default: ${{ vars.REFERENCE_REGISTRY }} FREE_DISK_SPACE: description: 'Free up disk space before building' type: boolean default: false RELEASE_REGISTRY: - description: 'Test registry to publish to' + description: "Test registry to publish to. Defaults to the caller's RELEASE_REGISTRY variable." type: string + default: ${{ vars.RELEASE_REGISTRY }} S3_S9PKS_BASE_URL: - description: 'S3 base URL for package uploads' + description: "S3 base URL for package uploads. Defaults to the caller's S3_S9PKS_BASE_URL variable." + type: string + default: ${{ vars.S3_S9PKS_BASE_URL }} + REGISTRY_PROXY: + description: "Proxy URL start-cli uses to reach the registries, e.g. socks5h://proxy.example:9050 for .onion registries. The proxy must already be reachable from the runner. Defaults to the caller's REGISTRY_PROXY variable." type: string + default: ${{ vars.REGISTRY_PROXY }} secrets: DEV_KEY: description: 'Developer signing key' @@ -43,6 +49,11 @@ jobs: - name: Install start-cli uses: Start9Labs/start-technologies/.github/actions/install-start-cli@master + - name: Configure registry proxy + uses: Start9Labs/start-technologies/.github/actions/configure-registry-proxy@master + with: + proxy: ${{ inputs.REGISTRY_PROXY }} + - name: Extract package ID and version id: extract uses: Start9Labs/start-technologies/.github/actions/extract-version@master @@ -53,6 +64,10 @@ jobs: PACKAGE_ID="${{ steps.extract.outputs.package_id }}" VERSION="${{ steps.extract.outputs.version }}" REFERENCE_REGISTRY="${{ inputs.REFERENCE_REGISTRY }}" + if [ -z "$REFERENCE_REGISTRY" ]; then + echo "::error::No reference registry: set the REFERENCE_REGISTRY variable or pass the input." + exit 1 + fi # hello-world is the canonical package scaffold, not a released package. # Skipping it here lets every caller (including hello-world's own) use the @@ -106,6 +121,7 @@ jobs: FREE_DISK_SPACE: ${{ inputs.FREE_DISK_SPACE }} RELEASE_REGISTRY: ${{ inputs.RELEASE_REGISTRY }} S3_S9PKS_BASE_URL: ${{ inputs.S3_S9PKS_BASE_URL }} + REGISTRY_PROXY: ${{ inputs.REGISTRY_PROXY }} secrets: DEV_KEY: ${{ secrets.DEV_KEY }} S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }} diff --git a/projects/start-sdk/docs/package-template/.forgejo/workflows/release.yml b/projects/start-sdk/docs/package-template/.forgejo/workflows/release.yml index b7f79e3b6a..2613e93970 100644 --- a/projects/start-sdk/docs/package-template/.forgejo/workflows/release.yml +++ b/projects/start-sdk/docs/package-template/.forgejo/workflows/release.yml @@ -7,9 +7,6 @@ name: Release jobs: release: uses: https://github.com/Start9Labs/start-technologies/.forgejo/workflows/release.yml@master - with: - RELEASE_REGISTRY: ${{ vars.RELEASE_REGISTRY }} - S3_S9PKS_BASE_URL: ${{ vars.S3_S9PKS_BASE_URL }} secrets: DEV_KEY: ${{ secrets.DEV_KEY }} S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }} diff --git a/projects/start-sdk/docs/package-template/.forgejo/workflows/tagAndRelease.yml b/projects/start-sdk/docs/package-template/.forgejo/workflows/tagAndRelease.yml index 74637996f5..def6c3f01c 100644 --- a/projects/start-sdk/docs/package-template/.forgejo/workflows/tagAndRelease.yml +++ b/projects/start-sdk/docs/package-template/.forgejo/workflows/tagAndRelease.yml @@ -12,10 +12,6 @@ concurrency: jobs: tag: uses: https://github.com/Start9Labs/start-technologies/.forgejo/workflows/tagAndRelease.yml@master - with: - REFERENCE_REGISTRY: ${{ vars.REFERENCE_REGISTRY }} - RELEASE_REGISTRY: ${{ vars.RELEASE_REGISTRY }} - S3_S9PKS_BASE_URL: ${{ vars.S3_S9PKS_BASE_URL }} secrets: DEV_KEY: ${{ secrets.DEV_KEY }} S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }} diff --git a/projects/start-sdk/docs/package-template/.github/workflows/release.yml b/projects/start-sdk/docs/package-template/.github/workflows/release.yml index 6dcef4a36a..4cd94c8866 100644 --- a/projects/start-sdk/docs/package-template/.github/workflows/release.yml +++ b/projects/start-sdk/docs/package-template/.github/workflows/release.yml @@ -8,9 +8,6 @@ on: jobs: release: uses: Start9Labs/start-technologies/.github/workflows/release.yml@master - with: - RELEASE_REGISTRY: ${{ vars.RELEASE_REGISTRY }} - S3_S9PKS_BASE_URL: ${{ vars.S3_S9PKS_BASE_URL }} secrets: DEV_KEY: ${{ secrets.DEV_KEY }} S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }} diff --git a/projects/start-sdk/docs/package-template/.github/workflows/tagAndRelease.yml b/projects/start-sdk/docs/package-template/.github/workflows/tagAndRelease.yml index f0008516f1..bfc0a69056 100644 --- a/projects/start-sdk/docs/package-template/.github/workflows/tagAndRelease.yml +++ b/projects/start-sdk/docs/package-template/.github/workflows/tagAndRelease.yml @@ -12,10 +12,6 @@ concurrency: jobs: tag: uses: Start9Labs/start-technologies/.github/workflows/tagAndRelease.yml@master - with: - REFERENCE_REGISTRY: ${{ vars.REFERENCE_REGISTRY }} - RELEASE_REGISTRY: ${{ vars.RELEASE_REGISTRY }} - S3_S9PKS_BASE_URL: ${{ vars.S3_S9PKS_BASE_URL }} secrets: DEV_KEY: ${{ secrets.DEV_KEY }} S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }} diff --git a/projects/start-sdk/docs/src/project-structure.md b/projects/start-sdk/docs/src/project-structure.md index 126d4c9240..37041dcd55 100644 --- a/projects/start-sdk/docs/src/project-structure.md +++ b/projects/start-sdk/docs/src/project-structure.md @@ -189,10 +189,6 @@ concurrency: jobs: tag: uses: Start9Labs/start-technologies/.github/workflows/tagAndRelease.yml@master - with: - REFERENCE_REGISTRY: ${{ vars.REFERENCE_REGISTRY }} - RELEASE_REGISTRY: ${{ vars.RELEASE_REGISTRY }} - S3_S9PKS_BASE_URL: ${{ vars.S3_S9PKS_BASE_URL }} secrets: DEV_KEY: ${{ secrets.DEV_KEY }} S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }} @@ -201,6 +197,8 @@ jobs: contents: write ``` +The reusable workflows read `REFERENCE_REGISTRY`, `RELEASE_REGISTRY`, `S3_S9PKS_BASE_URL` and `REGISTRY_PROXY` from the calling repository's variables, including organization variables. Set them there; pass an input of the same name under `with:` only to override one for a single repo's workflow. Secrets are not read this way and must still be passed. + **release.yml** -- publishes on manual tag push, for re-releases or testing. This workflow only triggers on manually pushed tags — tags created by tagAndRelease (via `GITHUB_TOKEN`) do not trigger it: ```yaml @@ -214,9 +212,6 @@ on: jobs: release: uses: Start9Labs/start-technologies/.github/workflows/release.yml@master - with: - RELEASE_REGISTRY: ${{ vars.RELEASE_REGISTRY }} - S3_S9PKS_BASE_URL: ${{ vars.S3_S9PKS_BASE_URL }} secrets: DEV_KEY: ${{ secrets.DEV_KEY }} S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }} @@ -225,6 +220,8 @@ jobs: contents: write ``` +To publish to registries served over Tor, run a Tor SOCKS proxy the runners can reach and set `REGISTRY_PROXY` to its URL, such as `socks5h://tor-proxy.example:9050`. The `socks5h` scheme resolves names through the proxy, which `.onion` addresses require. Both workflows then route every `start-cli` registry request through it. The workflows do not start a proxy themselves. + **syncNext.yml** -- carries every change that lands on the base branch onto the paired `next` iteration branch, so `next` never falls behind what has already shipped: ```yaml From 926e4aa82f841c37e1e62b80defeab9075f629d2 Mon Sep 17 00:00:00 2001 From: Matt Hill <9935159+MattDHill@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:19:04 -0700 Subject: [PATCH 09/38] feat(sdk): delete excluded paths and prune removed volumes in backups (#4800) * feat(sdk): add deleteExcluded sync option for backups rsync's --delete never removes paths matching --exclude on the receiver, so excluding a path from an existing sync leaves its stale copy in every backup taken before the change, and restores bring it back. The new `deleteExcluded` option passes --delete-excluded so a package can drop a regenerable cache from backups and reclaim its space. Co-Authored-By: Claude Opus 5.5 * docs(sdk): clarify backup exclusion cleanup scope Proposed changes for #4800. Scope cleanup to the next sync to the same target; other targets and retained read-only snapshots keep their contents. Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * feat(sdk): always delete excluded paths and prune removed backup volumes Per review: there is no case for keeping excluded data, so the deleteExcluded flag is dropped and syncs with `delete` pass --delete-excluded. A backup also removes entries of the backup's volumes/ directory that no sync writes into, so a volume dropped from the backup set no longer lingers in existing backups. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(sdk): keep volumes under ancestor backup paths and skip symlinked volumes root A sync targeting the backup root (or any ancestor of volumes/) now keeps every volume, dot-prefixed volume names are no longer mistaken for parent traversal, and pruning never traverses a volumes root that is not a real directory. Co-Authored-By: helix-white <267227783+helix-a@users.noreply.github.com> Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: helix-white <267227783+helix-a@users.noreply.github.com> Co-authored-by: helix-red <355572797+helix-red@users.noreply.github.com> --- .../minor-changed-backup-prunes-stale-data.md | 5 + projects/start-sdk/docs/src/recipe-backups.md | 4 +- projects/start-sdk/lib/backup/Backups.ts | 79 ++++++++--- .../start-sdk/lib/test/backup.sync.test.ts | 127 ++++++++++++++++++ .../ts-modules/start-core/lib/types.ts | 2 +- 5 files changed, 197 insertions(+), 20 deletions(-) create mode 100644 projects/start-sdk/changelog/minor-changed-backup-prunes-stale-data.md create mode 100644 projects/start-sdk/lib/test/backup.sync.test.ts diff --git a/projects/start-sdk/changelog/minor-changed-backup-prunes-stale-data.md b/projects/start-sdk/changelog/minor-changed-backup-prunes-stale-data.md new file mode 100644 index 0000000000..cf37ef8c3c --- /dev/null +++ b/projects/start-sdk/changelog/minor-changed-backup-prunes-stale-data.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Backups no longer keep stale data: syncs with `delete` (the default) also remove paths matching `exclude` from the target, and a backup removes volumes no longer in the backup set from the target being updated. diff --git a/projects/start-sdk/docs/src/recipe-backups.md b/projects/start-sdk/docs/src/recipe-backups.md index 46faddc056..47418e0a19 100644 --- a/projects/start-sdk/docs/src/recipe-backups.md +++ b/projects/start-sdk/docs/src/recipe-backups.md @@ -4,9 +4,9 @@ Every StartOS package must define a backup strategy. The SDK provides builders f ## Solution -Use `sdk.setupBackups()` with the appropriate builder. `sdk.Backups.ofVolumes('main')` for simple volume snapshots. `sdk.Backups.withPgDump()` for PostgreSQL (handles dump and restore). `sdk.Backups.withMysqlDump()` and `sdk.Backups.withMariadbDump()` dump MySQL and MariaDB, though a copied volume is usually the better choice for those (see [Databases](#databases-copy-the-volume-or-dump-it)). Chain `.addVolume('name')` for additional volumes. Use `.addSync({ dataPath, backupPath })` to select paths within a volume rather than copying the whole volume. Both forms use incremental rsync and skip unchanged files. +Use `sdk.setupBackups()` with the appropriate builder. `sdk.Backups.ofVolumes('main')` for simple volume snapshots. `sdk.Backups.withPgDump()` for PostgreSQL (handles dump and restore). `sdk.Backups.withMysqlDump()` and `sdk.Backups.withMariadbDump()` dump MySQL and MariaDB, though a copied volume is usually the better choice for those (see [Databases](#databases-copy-the-volume-or-dump-it)). Chain `.addVolume('name')` for additional volumes. Use `.addSync({ dataPath, backupPath })` to select paths within a volume rather than copying the whole volume. Both forms use incremental rsync and skip unchanged files. To leave out a regenerable cache, pass `backupOptions: { exclude: ['/cache/'] }` on the sync; patterns are rsync patterns relative to `dataPath`. The next backup to a target removes excluded paths, and volumes no longer in the backup set, left there by an earlier backup. -A restore installs the s9pk stored in the backup, so it runs that version's own backup and restore code; the current version's migrations run on the update after it. Changing the backup set never affects backups taken before the change. +A restore installs the s9pk stored in the backup, so it runs that version's own backup and restore code; the current version's migrations run on the update after it. Backups on other targets and retained read-only snapshots keep their original contents. > [!NOTE] > Because the service is stopped for the duration of the backup, your backup logic runs against a quiescent volume — nothing is writing to the data while it is copied or dumped. StartOS restarts the service automatically once the backup finishes, but only if it was running when the backup began; a service that was already stopped stays stopped. diff --git a/projects/start-sdk/lib/backup/Backups.ts b/projects/start-sdk/lib/backup/Backups.ts index f6e61ef88e..e024eb9e46 100644 --- a/projects/start-sdk/lib/backup/Backups.ts +++ b/projects/start-sdk/lib/backup/Backups.ts @@ -1,6 +1,7 @@ import * as T from '@start9labs/start-core/types' import * as child_process from 'child_process' import * as fs from 'fs/promises' +import * as path from 'path' import { Affine, asError } from '../util' import { InitKind, InitScript } from '@start9labs/start-core/inits' import { CommandOptions, SubContainer, execFile } from '../util/SubContainer' @@ -11,6 +12,7 @@ import { } from '@start9labs/start-core/util/FullProgressTracker' const BACKUP_HOST_PATH = '/media/startos/backup' +const BACKUP_VOLUMES_PATH = `${BACKUP_HOST_PATH}/volumes` const BACKUP_CONTAINER_MOUNT = '/backup-target' const MARIADB_SHUTDOWN_TIMEOUT = 120_000 @@ -1005,6 +1007,11 @@ export class Backups implements InitScript { phase.complete() } + await pruneBackupVolumes( + BACKUP_VOLUMES_PATH, + this.backupSet.map(s => s.backupPath), + ) + const dataVersion = await effects.getDataVersion() if (dataVersion) await fs.writeFile('/media/startos/backup/dataVersion.txt', dataVersion, { @@ -1105,6 +1112,56 @@ export class Backups implements InitScript { } } +/** + * Removes entries of the backup's volumes directory disjoint from every backup path. + * Leaves a volumes root that is not a real directory untouched. + */ +export async function pruneBackupVolumes( + volumesDir: string, + backupPaths: string[], +) { + const kept = new Set() + for (const backupPath of backupPaths) { + const parts = path.posix.relative(volumesDir, backupPath).split('/') + const volume = parts[0]! + if (volume === '' || parts.every(part => part === '..')) return + if (volume !== '..') kept.add(volume) + } + const metadata = await fs.lstat(volumesDir).catch(e => { + if (e?.code === 'ENOENT') return undefined + throw e + }) + if (!metadata?.isDirectory()) return + const entries = await fs.readdir(volumesDir) + for (const entry of entries) { + if (!kept.has(entry)) { + await fs.rm(path.posix.join(volumesDir, entry), { + recursive: true, + force: true, + }) + } + } +} + +export function rsyncArgs( + srcPath: string, + dstPath: string, + options: T.SyncOptions, +) { + return [ + ...(options.delete ? ['--delete', '--delete-excluded'] : []), + ...options.exclude.map(x => `--exclude=${x}`), + '-rlptgoAXH', + '--partial', + '--inplace', + '--timeout=300', + '--info=progress2', + // --no-inc-recursive's full pre-scan times out large backups. + srcPath, + dstPath, + ] +} + async function runRsync(rsyncOptions: { srcPath: string dstPath: string @@ -1118,23 +1175,11 @@ async function runRsync(rsyncOptions: { await fs.mkdir(dstPath, { recursive: true }) - const command = 'rsync' - const args: string[] = [] - if (options.delete) { - args.push('--delete') - } - for (const exclude of options.exclude) { - args.push(`--exclude=${exclude}`) - } - args.push('-rlptgoAXH') - args.push('--partial') - args.push('--inplace') - args.push('--timeout=300') - args.push('--info=progress2') - // --no-inc-recursive's full pre-scan times out large backups. - args.push(srcPath) - args.push(dstPath) - const spawned = child_process.spawn(command, args, { detached: true }) + const spawned = child_process.spawn( + 'rsync', + rsyncArgs(srcPath, dstPath, options), + { detached: true }, + ) let percentage = 0.0 spawned.stdout.on('data', (data: unknown) => { const lines = String(data).replace(/\r/g, '\n').split('\n') diff --git a/projects/start-sdk/lib/test/backup.sync.test.ts b/projects/start-sdk/lib/test/backup.sync.test.ts new file mode 100644 index 0000000000..18d4945e59 --- /dev/null +++ b/projects/start-sdk/lib/test/backup.sync.test.ts @@ -0,0 +1,127 @@ +import { execFileSync } from 'child_process' +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'fs' +import { readdir } from 'fs/promises' +import { tmpdir } from 'os' +import { join } from 'path' +import { + DEFAULT_OPTIONS, + pruneBackupVolumes, + rsyncArgs, +} from '../backup/Backups' + +describe('rsyncArgs exclusions', () => { + let root: string + let src: string + let dst: string + + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'rsync-args-')) + src = join(root, 'src') + '/' + dst = join(root, 'dst') + '/' + for (const dir of [src, dst]) { + mkdirSync(join(dir, 'cache'), { recursive: true }) + writeFileSync(join(dir, 'cache', 'thumb'), 'x') + } + writeFileSync(join(src, 'data'), 'x') + }) + + afterEach(() => rmSync(root, { recursive: true, force: true })) + + const sync = (options: Partial) => + execFileSync( + 'rsync', + rsyncArgs(src, dst, { ...DEFAULT_OPTIONS, ...options }), + ) + + it('removes an excluded path already in the target', () => { + sync({ exclude: ['/cache/'] }) + expect(existsSync(join(dst, 'data'))).toBe(true) + expect(existsSync(join(dst, 'cache'))).toBe(false) + }) + + it('leaves the target untouched without delete', () => { + sync({ exclude: ['/cache/'], delete: false }) + expect(existsSync(join(dst, 'data'))).toBe(true) + expect(existsSync(join(dst, 'cache'))).toBe(true) + }) +}) + +describe('pruneBackupVolumes', () => { + let volumes: string + + beforeEach(() => { + volumes = join(mkdtempSync(join(tmpdir(), 'backup-volumes-')), 'volumes') + for (const v of ['main', 'db', 'removed']) { + mkdirSync(join(volumes, v), { recursive: true }) + writeFileSync(join(volumes, v, 'file'), 'x') + } + }) + + afterEach(() => rmSync(join(volumes, '..'), { recursive: true, force: true })) + + it('removes volumes no backup path lies within', async () => { + await pruneBackupVolumes(volumes, [ + `${volumes}/main/`, + `${volumes}/db/pgdata/`, + `${join(volumes, '..')}/other/`, + ]) + expect((await readdir(volumes)).sort()).toEqual(['db', 'main']) + }) + + it('keeps every volume when a backup path is the volumes directory', async () => { + await pruneBackupVolumes(volumes, [`${volumes}/`]) + expect((await readdir(volumes)).sort()).toEqual(['db', 'main', 'removed']) + }) + + it('keeps every volume when a sync targets the backup root', async () => { + await pruneBackupVolumes(volumes, [join(volumes, '..')]) + expect((await readdir(volumes)).sort()).toEqual(['db', 'main', 'removed']) + expect(readFileSync(join(volumes, 'main', 'file'), 'utf8')).toBe('x') + }) + + it('keeps a custom volume target whose name starts with two dots', async () => { + const custom = join(volumes, '..cache') + mkdirSync(custom) + writeFileSync(join(custom, 'file'), 'current') + + await pruneBackupVolumes(volumes, [`${custom}/`]) + + expect(await readdir(volumes)).toEqual(['..cache']) + expect(readFileSync(join(custom, 'file'), 'utf8')).toBe('current') + }) + + it('prunes every volume when a sync targets a sibling directory', async () => { + await pruneBackupVolumes(volumes, [`${volumes}-archive/`]) + expect(await readdir(volumes)).toEqual([]) + }) + + it('prunes every volume when no sync selects one', async () => { + await pruneBackupVolumes(volumes, []) + expect(await readdir(volumes)).toEqual([]) + }) + + it('leaves a symlink volumes root and its target untouched', async () => { + const liveData = join(volumes, '..', 'live-data') + mkdirSync(liveData) + writeFileSync(join(liveData, 'file'), 'keep') + rmSync(volumes, { recursive: true, force: true }) + symlinkSync(liveData, volumes, 'dir') + + await pruneBackupVolumes(volumes, []) + expect(readFileSync(join(liveData, 'file'), 'utf8')).toBe('keep') + }) + + it('tolerates a backup with no volumes directory', async () => { + await expect( + pruneBackupVolumes(join(volumes, 'missing'), []), + ).resolves.toBeUndefined() + }) +}) diff --git a/shared-libs/ts-modules/start-core/lib/types.ts b/shared-libs/ts-modules/start-core/lib/types.ts index e5b2c81f4a..ff5428db5a 100644 --- a/shared-libs/ts-modules/start-core/lib/types.ts +++ b/shared-libs/ts-modules/start-core/lib/types.ts @@ -176,7 +176,7 @@ export type EffectMethod = { /** Options for rsync-based file synchronization (used in backup/restore). */ export type SyncOptions = { - /** delete files that exist in the target directory, but not in the source directory */ + /** delete files that exist in the target directory, but not in the source directory, including paths matching `exclude` */ delete: boolean /** do not sync files with paths that match these patterns */ exclude: string[] From b67bf47ae2f6684e913f71137abd29e55c16a9b9 Mon Sep 17 00:00:00 2001 From: Helix the White <267227783+helix-white@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:10:24 -0700 Subject: [PATCH 10/38] fix(security): refresh StartOS/StartWRT kernels and certificate trust (#4783) * fix(os): refresh vendor kernels and router certificate trust Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * style(build): omit whitespace-only patch context Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * fix(start-wrt): backport upstream certificate distrust Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * docs(security): address release review and trust wording Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * fix(start-os): backport Debian-signed forky kernel packages Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * refactor(build): confine temporary kernel backport bridge Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * fix(build): resolve kernel bridge include from owning makefile Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol --------- Co-authored-by: helix-white <267227783+helix-a@users.noreply.github.com> --- .github/workflows/start-wrt.yaml | 3 + .github/workflows/startos-image.yaml | 10 ++ AGENTS.md | 1 + NOTICE.md | 4 +- projects/start-os/AGENTS.md | 6 + projects/start-os/build.mk | 9 +- .../start-os/build/image-recipe/Dockerfile | 1 + .../start-os/build/image-recipe/README.md | 29 ++-- projects/start-os/build/image-recipe/build.sh | 18 ++- .../image-recipe/kernel-backports/AGENTS.md | 39 +++++ .../image-recipe/kernel-backports/CLAUDE.md | 1 + .../image-recipe/kernel-backports/README.md | 24 +++ .../build-kernel-backports.sh | 60 +++++++ .../image-recipe/kernel-backports/build.mk | 11 ++ .../kernel-backports/kernel-backports.conf | 7 + .../kernel-backports/repack-kernel-deb.sh | 84 ++++++++++ .../image-recipe/kernel-backports/stage.sh | 17 ++ .../image-recipe/kernel-backports/test.sh | 147 ++++++++++++++++++ .../verify-kernel-backports.sh | 17 ++ .../build/tests/backports-pref-test.sh | 2 +- .../build/tests/kernel-kbuild-test.sh | 28 ++++ .../patch-security-kernel-backports.md | 5 + .../changelog/patch-security-pi-tcp-kernel.md | 5 + projects/start-os/debian/postinst | 1 + projects/start-wrt/AGENTS.md | 8 +- projects/start-wrt/build.mk | 12 +- projects/start-wrt/build/gen-kernel-patch.sh | 2 +- .../start-wrt/build/test-ca-certificates.sh | 31 ++++ ...h-security-kernel-and-certificate-trust.md | 6 + projects/start-wrt/openwrt-overlay/README.md | 1 + .../patches/0002-blacklist-certs.patch | 24 +++ .../target/linux/generic/kernel-6.18 | 4 +- .../0000-spacemit-k1-vendor-kernel.patch | 52 +++---- ...1-ca-certificates-distrust-emsign-g3.patch | 21 +++ 34 files changed, 629 insertions(+), 61 deletions(-) create mode 100644 projects/start-os/build/image-recipe/kernel-backports/AGENTS.md create mode 100644 projects/start-os/build/image-recipe/kernel-backports/CLAUDE.md create mode 100644 projects/start-os/build/image-recipe/kernel-backports/README.md create mode 100755 projects/start-os/build/image-recipe/kernel-backports/build-kernel-backports.sh create mode 100644 projects/start-os/build/image-recipe/kernel-backports/build.mk create mode 100644 projects/start-os/build/image-recipe/kernel-backports/kernel-backports.conf create mode 100755 projects/start-os/build/image-recipe/kernel-backports/repack-kernel-deb.sh create mode 100755 projects/start-os/build/image-recipe/kernel-backports/stage.sh create mode 100755 projects/start-os/build/image-recipe/kernel-backports/test.sh create mode 100755 projects/start-os/build/image-recipe/kernel-backports/verify-kernel-backports.sh create mode 100755 projects/start-os/build/tests/kernel-kbuild-test.sh create mode 100644 projects/start-os/changelog/patch-security-kernel-backports.md create mode 100644 projects/start-os/changelog/patch-security-pi-tcp-kernel.md create mode 100755 projects/start-wrt/build/test-ca-certificates.sh create mode 100644 projects/start-wrt/changelog/patch-security-kernel-and-certificate-trust.md create mode 100644 projects/start-wrt/openwrt-overlay/package/system/ca-certificates/patches/0002-blacklist-certs.patch create mode 100644 projects/start-wrt/openwrt-patches/0011-ca-certificates-distrust-emsign-g3.patch diff --git a/.github/workflows/start-wrt.yaml b/.github/workflows/start-wrt.yaml index 4ca7842188..8dd389d240 100644 --- a/.github/workflows/start-wrt.yaml +++ b/.github/workflows/start-wrt.yaml @@ -165,6 +165,9 @@ jobs: - name: Build image run: make start-wrt-image + - name: Verify the image trust store + run: make start-wrt-ca-test + - uses: actions/upload-artifact@v7 with: name: startwrt-openwrt-image diff --git a/.github/workflows/startos-image.yaml b/.github/workflows/startos-image.yaml index 72fa79a815..0af2952411 100644 --- a/.github/workflows/startos-image.yaml +++ b/.github/workflows/startos-image.yaml @@ -168,6 +168,16 @@ jobs: run: make start-os-img if: ${{ inputs.platform == 'raspberrypi' }} + - name: Archive kernel backport packages + uses: actions/upload-artifact@v7 + if: ${{ inputs.platform == 'x86_64' || inputs.platform == 'aarch64' }} + with: + name: ${{ inputs.platform }}.kernel-backports + path: results/kernel-backports/ + if-no-files-found: error + retention-days: 14 + compression-level: 0 + # Images are already compressed, so the artifacts are stored as-is. - uses: actions/upload-artifact@v7 with: diff --git a/AGENTS.md b/AGENTS.md index 44e6f587f3..2c8a3c34cc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -211,6 +211,7 @@ the source of truth. ## Releases +- **Assess kernel security before OS releases.** The release author compares each image's installed kernel, including vendor patches, with current stable/vendor security releases and outstanding advisories. Review every fixed-version kernel source through that assessment; an upstream source commit or accepted source upload is not an installable vendor package. Kernel security updates take priority over NVIDIA compatibility: test candidate releases on NVIDIA hardware before shipping, and report regressions rather than freezing a vulnerable kernel. - **Changelog and Highlights compilation is shared by tag CI, builds, and the release script.** `docs-sync-on-tag.yml` uses the `docs-publish` App to compile tagged fragments under `## []`, write the generated history to `master`, archive each release's published notes there, and consume only fragments unchanged since the tag. It retains the generated history and every locale's notes on `live-docs`. Re-running an unchanged tag is idempotent; changing an already-compiled release's fragments fails rather than overwriting history. `manage-release.sh` renders the same changelog from the commit being tagged, embeds that version's changelog section in an expandable GitHub release section, and attaches the full history as `CHANGELOG.md`. Releases stay in draft until the tag exists; promotion follows publication. A retry resumes a draft missing its notes or changelog instead of treating the release's existence as completion. The shared Node compiler formats generated Markdown with the root `package.json`'s pinned Prettier and `.prettierrc.json` before committing history or attaching it. - **Cutting `/v` is what advances `live-docs` for that product.** StartOS RC tags neither publish books nor consume changelog fragments. [`.github/workflows/docs-sync-on-tag.yml`](.github/workflows/docs-sync-on-tag.yml) takes the tagged tree **whole**, then puts every _other_ `projects/*` back on the release it is on. So a tag moves its own project, the shared libraries beneath it (`shared-libs/`), and the repo root — and nothing another product owns. The shared `projects/start-docs/` site tree rides along only with a product that ships a book, but in `versions.conf` a tag speaks only for its own book's line: other products keep the label `live-docs` publishes, and StartOS and StartWRT tags derive their own from the version (`start-wrt/v1.3.0` publishes under `1.3.x`). The `start-tunnel` and `packaging` lines are hand-maintained and must name the label you want **before** you tag. A bookless release (start-cli, start-registry) still advances its own project and the shared tree; it just leaves the site alone, so no deploy fires. Nothing moves backwards: a tag behind a release already synced — a deb release adopts the commit alpha built, often older than a tag cut before it — still advances its own project but leaves the shared trees where the newer release put them, and a tag behind its own product's last release publishes its book alone. - **Cut every release with [`scripts/manage-release.sh`](scripts/manage-release.sh)** — `./scripts/manage-release.sh release ` (`start-os`, `start-cli`, `start-tunnel`, `start-registry`, `start-sdk`, `start-wrt`); `--help` lists the individual subcommands and env vars. A product's version is read from its manifest (`Cargo.toml`, or `package.json` for the SDK), and its git tag / GitHub release is `/v`. **StartOS is the exception:** its version carries a revision segment SemVer cannot express (`0.4.0.1`), so the **root `package.json`** holds it and `projects/start-os/Cargo.toml` carries only a `0.4.0-rev.1` label — never a comparand, since a SemVer prerelease sorts _below_ its release. Read it via `build/env/version.sh`; see [`shared-libs/crates/start-core/VERSION_BUMP.md`](shared-libs/crates/start-core/VERSION_BUMP.md). diff --git a/NOTICE.md b/NOTICE.md index bf878ed1c9..59e58b4672 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -13,8 +13,8 @@ license and is not redistributed in this repository. ### `projects/start-wrt/openwrt-overlay/`, `projects/start-wrt/openwrt-patches/` GPL-licensed, mostly GPL-2.0-only. Files added to, and patches against, the -OpenWrt build tree — copyright SpaceMiT Ltd., OpenWrt.org and the Linux kernel -contributors. Sixteen carry an explicit `SPDX-License-Identifier` header. Full +OpenWrt build tree — copyright SpaceMiT Ltd., OpenWrt.org, the Linux kernel +contributors and the Debian ca-certificates contributors. Sixteen carry an explicit `SPDX-License-Identifier` header. Full text: [`projects/start-wrt/openwrt-overlay/COPYING`](projects/start-wrt/openwrt-overlay/COPYING). Details: [`projects/start-wrt/openwrt-overlay/README.md`](projects/start-wrt/openwrt-overlay/README.md). diff --git a/projects/start-os/AGENTS.md b/projects/start-os/AGENTS.md index e9d16feda7..bb3c12f73f 100644 --- a/projects/start-os/AGENTS.md +++ b/projects/start-os/AGENTS.md @@ -152,6 +152,12 @@ make start-os-deb # Debian package (start-os-squashfs for the squa `make start-core-ts-bindings` regenerates the TS bindings from the Rust types (see [Cross-layer changes](#cross-layer-changes)). +#### Kernel backport packages + +Before changing or retiring the signed-kernel bridge, read +[`build/image-recipe/kernel-backports/AGENTS.md`](build/image-recipe/kernel-backports/AGENTS.md). +That directory owns its build rules, tests, configuration and removal boundary. + #### Deploying to a device These targets push to a **live device** and are slow/destructive — be deliberate. For devices on the same network: diff --git a/projects/start-os/build.mk b/projects/start-os/build.mk index f33c6af9a0..880a34070a 100644 --- a/projects/start-os/build.mk +++ b/projects/start-os/build.mk @@ -38,7 +38,7 @@ start-os-upgrade-identity-test: projects/start-os/build/tests/upgrade-identity.t start-os-grub-test: projects/start-os/build/tests/grub-overrides-test.sh projects/start-os/build/lib/grub-user.cfg projects/start-os/build/lib/scripts/nvme-isolation-test projects/start-os/debian/postinst projects/start-os/build/image-recipe/raspberrypi/squashfs/etc/default/grub.d/raspberrypi.cfg ./projects/start-os/build/tests/grub-overrides-test.sh -start-os-scripts-test: start-os-grub-test start-os-forward-transport-test start-os-upgrade-identity-test projects/start-os/build/tests/dns-config-test.sh projects/start-os/build/lib/resolved.conf projects/start-os/container-runtime/deb-install.sh projects/start-os/container-runtime/update-image.sh projects/start-os/build/lib/scripts/normalize-fstab projects/start-os/build/tests/normalize-fstab-test.sh projects/start-os/build/image-recipe/raspberrypi/img/usr/lib/startos/scripts/init_resize.sh projects/start-os/build/tests/init-resize-test.sh projects/start-os/build/image-recipe/build.sh projects/start-os/build/tests/backports-pref-test.sh projects/start-os/build/lib/scripts/gather-debug-info projects/start-os/debian/postinst projects/start-os/build/tests/crash-diagnostics-test.sh projects/start-os/build/tests/btrfsmaintenance-test.sh projects/start-os/build/dpkg-deps/depends projects/start-os/build/tests/runtime-package-upgrade-test.sh projects/start-os/build/tests/migration-images-test.sh projects/start-os/build/save-migration-images.sh +start-os-scripts-test: start-os-grub-test start-os-forward-transport-test start-os-upgrade-identity-test start-os-kbuild-test projects/start-os/build/tests/dns-config-test.sh projects/start-os/build/lib/resolved.conf projects/start-os/container-runtime/deb-install.sh projects/start-os/container-runtime/update-image.sh projects/start-os/build/lib/scripts/normalize-fstab projects/start-os/build/tests/normalize-fstab-test.sh projects/start-os/build/image-recipe/raspberrypi/img/usr/lib/startos/scripts/init_resize.sh projects/start-os/build/tests/init-resize-test.sh projects/start-os/build/image-recipe/build.sh projects/start-os/build/tests/backports-pref-test.sh projects/start-os/build/lib/scripts/gather-debug-info projects/start-os/debian/postinst projects/start-os/build/tests/crash-diagnostics-test.sh projects/start-os/build/tests/btrfsmaintenance-test.sh projects/start-os/build/dpkg-deps/depends projects/start-os/build/tests/runtime-package-upgrade-test.sh projects/start-os/build/tests/migration-images-test.sh projects/start-os/build/save-migration-images.sh ./projects/start-os/build/tests/migration-images-test.sh ./projects/start-os/build/tests/normalize-fstab-test.sh ./projects/start-os/build/tests/init-resize-test.sh @@ -56,6 +56,13 @@ projects/start-os/build/lib/migration-images/.done: projects/start-os/build/save ./projects/start-os/build/save-migration-images.sh projects/start-os/build/lib/migration-images touch $@ +# May be included from an isolated build directory. +include $(dir $(lastword $(MAKEFILE_LIST)))build/image-recipe/kernel-backports/build.mk + +.PHONY: start-os-kbuild-test +start-os-kbuild-test: projects/start-os/build/tests/kernel-kbuild-test.sh projects/start-os/build/image-recipe/build.sh + ./projects/start-os/build/tests/kernel-kbuild-test.sh + start-os-deb: results/$(BASENAME).deb results/$(BASENAME).deb: debian/build.sh build/common.mk build/bash-completion projects/start-os/build.mk $(call ls-files,projects/start-os/debian) $(STARTOS_TARGETS) diff --git a/projects/start-os/build/image-recipe/Dockerfile b/projects/start-os/build/image-recipe/Dockerfile index 13d1a80b09..71f67ecef4 100644 --- a/projects/start-os/build/image-recipe/Dockerfile +++ b/projects/start-os/build/image-recipe/Dockerfile @@ -8,6 +8,7 @@ RUN apt-get update && \ live-build \ procps \ binfmt-support \ + binutils \ qemu-utils \ qemu-user-static \ xorriso \ diff --git a/projects/start-os/build/image-recipe/README.md b/projects/start-os/build/image-recipe/README.md index 91f77f5000..650dbb6639 100644 --- a/projects/start-os/build/image-recipe/README.md +++ b/projects/start-os/build/image-recipe/README.md @@ -1,19 +1,22 @@ # StartOS Image Recipes -Code that uses `live-build` to create the StartOS live and installer -images. - -If you want to build a local image in the exact same environment used to build -official StartOS images, you can use the `run-local-build.sh` helper script: +`live-build` assembles the StartOS live and installer images inside the Debian +Docker builder defined here. Run the owning recipes from the repository root: ```bash -# Prerequisites -sudo apt-get install -y debspawn binfmt-support -sudo mkdir -p /etc/debspawn/ && echo "AllowUnsafePermissions=true" | sudo tee /etc/debspawn/global.toml - -# Build image -./run-local-build.sh +make start-os-iso PLATFORM=x86_64 +make start-os-img PLATFORM=raspberrypi ``` -In order for the build to work properly, you will need debspawn >= 0.5.1, the -build may fail with prior versions. +See [StartOS build prerequisites](../../AGENTS.md#prerequisites) for Docker, +architecture emulation and image tooling. `run-local-build.sh` is the recipe's +container wrapper and accepts the prepared StartOS `.deb` path. + +Generic x86/ARM images use the isolated +[signed-kernel bridge](kernel-backports/README.md). Its build rules, tests, +configuration and retirement boundary live in that directory. + +Raspberry Pi and other vendor kernels, and RISC-V kernel selection, are unchanged. +Both Pi `rpi-v8` and `rpi-2712` packages must remain available. The root +[kernel-security review requirements](../../../../AGENTS.md#releases) govern +release validation. diff --git a/projects/start-os/build/image-recipe/build.sh b/projects/start-os/build/image-recipe/build.sh index 0df502be09..87a27cbce5 100755 --- a/projects/start-os/build/image-recipe/build.sh +++ b/projects/start-os/build/image-recipe/build.sh @@ -84,7 +84,7 @@ PLATFORM_CONFIG_EXTRAS=() if [ "${IB_TARGET_PLATFORM}" = "raspberrypi" ]; then PLATFORM_CONFIG_EXTRAS+=( --firmware-binary false ) PLATFORM_CONFIG_EXTRAS+=( --firmware-chroot false ) - RPI_KERNEL_VERSION=6.18.33+rpt + RPI_KERNEL_VERSION=6.18.60+rpt PLATFORM_CONFIG_EXTRAS+=( --linux-packages linux-image-$RPI_KERNEL_VERSION ) PLATFORM_CONFIG_EXTRAS+=( --linux-flavours "rpi-v8 rpi-2712" ) elif [ "${IB_TARGET_PLATFORM}" = "rockchip64" ]; then @@ -128,6 +128,8 @@ mkdir -p config/packages.chroot/ cp $RESULTS_DIR/$IMAGE_BASENAME.deb config/packages.chroot/ dpkg-name config/packages.chroot/*.deb +"$SOURCE_DIR/kernel-backports/stage.sh" "$IB_SUITE" "$IB_TARGET_PLATFORM" "$IB_TARGET_ARCH" "$RESULTS_DIR" + mkdir -p config/includes.chroot/etc echo start > config/includes.chroot/etc/hostname cat > config/includes.chroot/etc/hosts << EOT @@ -233,7 +235,7 @@ Pin-Priority: -1 EOF else cat > config/archives/backports.pref <<-EOF -Package: linux-image-* linux-headers-* linux-base *nvidia* +Package: linux-image-* linux-headers-* linux-base* linux-binary-* linux-modules-* linux-kbuild-* *nvidia* Pin: release n=${IB_SUITE}-backports Pin-Priority: 500 EOF @@ -363,13 +365,14 @@ if [ "${NVIDIA}" = "1" ]; then echo "[nvidia-hook] Removed build dependencies." >&2 fi -# Install linux-kbuild for sign-file (Secure Boot module signing) KVER_ALL="\$(ls -1t /boot/vmlinuz-* 2>/dev/null | head -n1 | sed 's|.*/vmlinuz-||')" if [ -n "\${KVER_ALL}" ]; then - KBUILD_VER="\$(echo "\${KVER_ALL}" | grep -oP '^\d+\.\d+')" - if [ -n "\${KBUILD_VER}" ]; then - echo "[build] Installing linux-kbuild-\${KBUILD_VER} for Secure Boot support" >&2 - apt-get install -y "linux-kbuild-\${KBUILD_VER}" || echo "[build] WARNING: linux-kbuild-\${KBUILD_VER} not available" >&2 + KBUILD_PACKAGE="\$(apt-cache depends "linux-headers-\${KVER_ALL}" 2>/dev/null | awk '/Depends: linux-kbuild-/ { print \$2; exit }')" + if [ -n "\${KBUILD_PACKAGE}" ]; then + echo "[build] Installing \${KBUILD_PACKAGE} for Secure Boot support" >&2 + apt-get install -y "\${KBUILD_PACKAGE}" || echo "[build] WARNING: \${KBUILD_PACKAGE} not available" >&2 + else + echo "[build] WARNING: no kbuild dependency found for linux-headers-\${KVER_ALL}" >&2 fi fi @@ -428,6 +431,7 @@ else exit $EXIT fi retry lb chroot +"$SOURCE_DIR/kernel-backports/verify-kernel-backports.sh" chroot "$IB_TARGET_ARCH" # riscv64 binaries target RVA23, which the build host may lack. RUN_TARGET=() diff --git a/projects/start-os/build/image-recipe/kernel-backports/AGENTS.md b/projects/start-os/build/image-recipe/kernel-backports/AGENTS.md new file mode 100644 index 0000000000..4500149262 --- /dev/null +++ b/projects/start-os/build/image-recipe/kernel-backports/AGENTS.md @@ -0,0 +1,39 @@ +# Kernel bridge maintenance + +This directory is the complete temporary kernel backport implementation, including +its configuration, tests and Make rules. The parent image recipe may stage and +verify the bridge through its two hooks; keep package/snapshot/platform policy +inside this directory. + +Build with `make start-os-kernel-backports KERNEL_DEB_ARCH=amd64` or `arm64`. +Outputs are `results/kernel-backports///`. Run +`make start-os-kernel-backports-test` for focused coverage. Both targets use the +existing product build infrastructure. + +Signed kernel/module payload bytes and Debian signatures must survive +repackaging. Header compiler selectors may change with their package checksums; +the ABI and kernel configuration stay intact. Rebuilding or locally signing the +kernel is outside this bridge's contract. + +## Retirement + +Retire the bridge once official trixie-backports provides a patched signed kernel +and usable matching headers/compiler dependencies. Its version sorts below the +corresponding official backport. Never mix its forky ABI with official backports +modules or headers. + +The removal boundary is: + +- Delete this directory. +- Delete the two `kernel-backports/` calls in the parent `build.sh`. +- Delete this directory's Make include from `projects/start-os/build.mk`. +- Delete the `Archive kernel backport packages` step in `startos-image.yaml`. +- Remove the bridge's explicit `binutils` dependency from the image Dockerfile. +- Replace the bridge pointers in the parent README and StartOS AGENTS with normal + backports selection documentation. + +Keep the permanent family-wide backports preferences, target-header-based kbuild +lookup, their tests/Make target, and the image-built `GRUB_TOP_LEVEL` contract. +Retain the security changelog benefit, updating its kernel version if necessary. +Preserve incoming-image boot preference over retained higher-ABI kernels when +verifying the official-backport transition. diff --git a/projects/start-os/build/image-recipe/kernel-backports/CLAUDE.md b/projects/start-os/build/image-recipe/kernel-backports/CLAUDE.md new file mode 100644 index 0000000000..43c994c2d3 --- /dev/null +++ b/projects/start-os/build/image-recipe/kernel-backports/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/projects/start-os/build/image-recipe/kernel-backports/README.md b/projects/start-os/build/image-recipe/kernel-backports/README.md new file mode 100644 index 0000000000..724ae33a3e --- /dev/null +++ b/projects/start-os/build/image-recipe/kernel-backports/README.md @@ -0,0 +1,24 @@ +# Signed-kernel backport bridge + +This directory owns the forky bridge for generic trixie x86/ARM images, including +nonfree and NVIDIA variants. `stage.sh` adds a build-local archive; +`verify-kernel-backports.sh` checks it after chroot assembly and skips images +without that archive. The parent recipe contains only these two hooks. + +`kernel-backports.conf` owns the snapshot, ABI, package version, compiler and +archive-list path. Native APT verifies Debian signatures and package hashes from +the pinned snapshot; historical metadata expiry is disabled for that fixed input. +The signed kernel/module payload archives remain byte-identical. Header compiler +selectors and checksums use trixie's compiler while the ABI and kernel +configuration stay intact. Header directory timestamps are reproducible. + +`live-build` binds the flat file archive through its chroot-only archive facility. +`trusted=yes` applies to that generated archive, not the Debian network source. +Neither the source nor its deb files remain in the assembled image. APT selects +needed packages without installing every header into every image. + +The image check requires a sufficiently new installed kernel package, identical +module/boot binaries and incoming `GRUB_TOP_LEVEL`. Retained higher-ABI boot files +must not displace the incoming image when returning to official backports. + +Read [AGENTS.md](AGENTS.md) for builds, contracts and the removal boundary. diff --git a/projects/start-os/build/image-recipe/kernel-backports/build-kernel-backports.sh b/projects/start-os/build/image-recipe/kernel-backports/build-kernel-backports.sh new file mode 100755 index 0000000000..1cae360af5 --- /dev/null +++ b/projects/start-os/build/image-recipe/kernel-backports/build-kernel-backports.sh @@ -0,0 +1,60 @@ +#!/bin/bash +set -euo pipefail + +ARCH=$1 +OUTPUT_ROOT=$(realpath -m "$2") +SOURCE_DIR=$(realpath "$(dirname "${BASH_SOURCE[0]}")") +source "$SOURCE_DIR/kernel-backports.conf" +OUTPUT="$OUTPUT_ROOT/$KERNEL_BACKPORT_VERSION" +case "$ARCH" in + amd64|arm64) ;; + *) echo "No Debian-signed kernel bridge for $ARCH" >&2; exit 1 ;; +esac +WORK=$(mktemp -d) +trap 'rm -rf -- "$WORK"' EXIT +mkdir -p "$WORK"/{etc/apt.conf.d,etc/preferences.d,state/lists/partial,cache/archives/partial,log,downloads} "$OUTPUT" +chmod 755 "$WORK" +if [ "$(id -u)" -eq 0 ]; then + chown _apt "$WORK/downloads" +fi +touch "$WORK/state/status" +cat > "$WORK/apt.conf" < "$WORK/etc/sources.list" < "$WORK/plan" + +PACKAGES=() +while read -r filename; do + package=${filename%%_*} + case "$package" in + linux-*"$KERNEL_BACKPORT_ABI"*|linux-*-"$ARCH") + PACKAGES+=("$package=$KERNEL_BACKPORT_UPSTREAM_VERSION") ;; + esac +done < <(awk '/^\047/ { print $2 }' "$WORK/plan") +if [ "${#PACKAGES[@]}" -eq 0 ]; then + echo 'APT did not select any kernel packages' >&2 + exit 1 +fi +(cd "$WORK/downloads" && apt-get download "${PACKAGES[@]}") +for deb in "$WORK/downloads"/*.deb; do + "$SOURCE_DIR/repack-kernel-deb.sh" "$deb" "$OUTPUT" +done +( + cd "$OUTPUT" + dpkg-scanpackages . /dev/null > Packages + gzip -n -c Packages > Packages.gz +) +printf 'Kernel backports archive: %s\n' "$OUTPUT" diff --git a/projects/start-os/build/image-recipe/kernel-backports/build.mk b/projects/start-os/build/image-recipe/kernel-backports/build.mk new file mode 100644 index 0000000000..7cd002d472 --- /dev/null +++ b/projects/start-os/build/image-recipe/kernel-backports/build.mk @@ -0,0 +1,11 @@ +KERNEL_BACKPORTS_DIR := projects/start-os/build/image-recipe/kernel-backports +KERNEL_DEB_ARCH ?= $(shell dpkg --print-architecture) + +.PHONY: start-os-kernel-backports start-os-kernel-backports-test +start-os-kernel-backports: + FORCE_COMPAT=1 REQUIRES=debian ./build/os-compat/run-compat.sh ./$(KERNEL_BACKPORTS_DIR)/build-kernel-backports.sh $(KERNEL_DEB_ARCH) results/kernel-backports/$(KERNEL_DEB_ARCH) + +start-os-kernel-backports-test: $(wildcard $(KERNEL_BACKPORTS_DIR)/*.sh) $(KERNEL_BACKPORTS_DIR)/kernel-backports.conf + ./$(KERNEL_BACKPORTS_DIR)/test.sh + +start-os-scripts-test: start-os-kernel-backports-test diff --git a/projects/start-os/build/image-recipe/kernel-backports/kernel-backports.conf b/projects/start-os/build/image-recipe/kernel-backports/kernel-backports.conf new file mode 100644 index 0000000000..fd9f664634 --- /dev/null +++ b/projects/start-os/build/image-recipe/kernel-backports/kernel-backports.conf @@ -0,0 +1,7 @@ +KERNEL_BACKPORT_ARCHIVE_LIST=config/archives/kernel-backports.list.chroot +KERNEL_BACKPORT_SNAPSHOT=20261118T180000Z +KERNEL_BACKPORT_ABI=7.3.4+deb14 +KERNEL_BACKPORT_UPSTREAM_VERSION=7.3.4-1 +KERNEL_BACKPORT_VERSION=7.3.4-1~bpo13+1~start9.1 +KERNEL_BACKPORT_COMPILER=gcc-14-for-host +KERNEL_BACKPORT_MAINTAINER='Start9 Labs ' diff --git a/projects/start-os/build/image-recipe/kernel-backports/repack-kernel-deb.sh b/projects/start-os/build/image-recipe/kernel-backports/repack-kernel-deb.sh new file mode 100755 index 0000000000..ace10c30b2 --- /dev/null +++ b/projects/start-os/build/image-recipe/kernel-backports/repack-kernel-deb.sh @@ -0,0 +1,84 @@ +#!/bin/bash +set -euo pipefail + +SOURCE=$(realpath "$1") +OUTPUT=$(realpath -m "$2") +source "$(dirname "${BASH_SOURCE[0]}")/kernel-backports.conf" +WORK=$(mktemp -d) +trap 'rm -rf -- "$WORK"' EXIT + +PACKAGE=$(dpkg-deb -f "$SOURCE" Package) +ARCH=$(dpkg-deb -f "$SOURCE" Architecture) +UPSTREAM_VERSION=$(dpkg-deb -f "$SOURCE" Version) +if [ "$UPSTREAM_VERSION" != "$KERNEL_BACKPORT_UPSTREAM_VERSION" ]; then + echo "Unexpected kernel package version: $UPSTREAM_VERSION" >&2 + exit 1 +fi + +dpkg-deb --control "$SOURCE" "$WORK/control" +awk -v old="$UPSTREAM_VERSION" -v version="$KERNEL_BACKPORT_VERSION" \ + -v compiler="$KERNEL_BACKPORT_COMPILER" -v maintainer="$KERNEL_BACKPORT_MAINTAINER" \ + -v hash="$(sha256sum "$SOURCE" | cut -d' ' -f1)" ' +function replace_version(value, result, position) { + while ((position = index(value, old)) != 0) { + result = result substr(value, 1, position - 1) version + value = substr(value, position + length(old)) + } + return result value +} +/^[^ \t]/ { field = $1 } +/^Version:/ { print "Version: " version; next } +/^Maintainer:/ { + sub(/^Maintainer:/, "Original-Maintainer:") + print + print "Maintainer: " maintainer + next +} +field ~ /^(Depends|Pre-Depends|Recommends|Suggests|Breaks|Conflicts|Replaces|Provides):$/ { + $0 = replace_version($0) + gsub(/gcc-[0-9]+-for-host/, compiler) +} +{ print } +END { + print "Origin: Start9" + print "X-Start9-Upstream-SHA256: " hash +} +' "$WORK/control/control" > "$WORK/control.new" +mv "$WORK/control.new" "$WORK/control/control" + +# Preserve Debian's signed kernel, modules and ABI byte-for-byte. +DATA=$(ar t "$SOURCE" | grep '^data\.tar') +(cd "$WORK" && ar x "$SOURCE" debian-binary "$DATA") +if [[ "$PACKAGE" = linux-headers-* ]]; then + dpkg-deb --extract "$SOURCE" "$WORK/data" + mapfile -t selectors < <(find "$WORK/data" -name .kernelvariables -type f) + for selector in "${selectors[@]}"; do + cp -p "$selector" "$WORK/compiler-reference" + sed -i -E "/^CC =/s/gcc-[0-9]+$/${KERNEL_BACKPORT_COMPILER%-for-host}/" "$selector" + touch -r "$WORK/compiler-reference" "$selector" + relative=${selector#"$WORK/data/"} + hash=$(md5sum "$selector" | cut -d' ' -f1) + awk -v path="$relative" -v hash="$hash" ' + $2 == path { $0 = hash " " path } + { print } + ' "$WORK/control/md5sums" > "$WORK/md5sums.new" + mv "$WORK/md5sums.new" "$WORK/control/md5sums" + done + if [ "${#selectors[@]}" -gt 0 ]; then + DATA=data.tar.gz + # Extraction defers symlinks and leaves their parent timestamps nondeterministic. + find "$WORK/data" -type d -exec touch -d @0 {} + + tar --format=gnu --sort=name --owner=0 --group=0 --numeric-owner \ + -C "$WORK/data" -cf - . | gzip -n > "$WORK/$DATA" + fi +fi +tar --sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner \ + -C "$WORK/control" -cf - . | gzip -n > "$WORK/control.tar.gz" +(cd "$WORK" && ar rcD package.deb debian-binary control.tar.gz "$DATA") +if [[ "$PACKAGE" != linux-headers-* ]]; then + cmp <(ar p "$SOURCE" "$DATA") <(ar p "$WORK/package.deb" "$DATA") +fi +mkdir -p "$OUTPUT" +DEB="$OUTPUT/${PACKAGE}_${KERNEL_BACKPORT_VERSION}_${ARCH}.deb" +mv "$WORK/package.deb" "$DEB" +printf '%s\n' "$DEB" diff --git a/projects/start-os/build/image-recipe/kernel-backports/stage.sh b/projects/start-os/build/image-recipe/kernel-backports/stage.sh new file mode 100755 index 0000000000..f28a117ea9 --- /dev/null +++ b/projects/start-os/build/image-recipe/kernel-backports/stage.sh @@ -0,0 +1,17 @@ +#!/bin/bash +set -euo pipefail +SUITE=$1 +PLATFORM=$2 +ARCH=$3 +RESULTS_DIR=$4 +SOURCE_DIR=$(realpath "$(dirname "${BASH_SOURCE[0]}")") +source "$SOURCE_DIR/kernel-backports.conf" +case "$SUITE:${PLATFORM%%-*}" in + trixie:x86_64|trixie:aarch64) + ARCHIVE="$RESULTS_DIR/kernel-backports/$ARCH" + "$SOURCE_DIR/build-kernel-backports.sh" "$ARCH" "$ARCHIVE" + mkdir -p "$(dirname "$KERNEL_BACKPORT_ARCHIVE_LIST")" + printf 'deb [trusted=yes] file://%s ./\n' "$ARCHIVE/$KERNEL_BACKPORT_VERSION" \ + > "$KERNEL_BACKPORT_ARCHIVE_LIST" + ;; +esac diff --git a/projects/start-os/build/image-recipe/kernel-backports/test.sh b/projects/start-os/build/image-recipe/kernel-backports/test.sh new file mode 100755 index 0000000000..65dbf3ccff --- /dev/null +++ b/projects/start-os/build/image-recipe/kernel-backports/test.sh @@ -0,0 +1,147 @@ +#!/bin/bash +set -euo pipefail +RECIPE=$(realpath "$(dirname "${BASH_SOURCE[0]}")") +source "$RECIPE/kernel-backports.conf" +WORK=$(mktemp -d) +trap 'rm -rf -- "$WORK"' EXIT + +fail() { echo "FAIL: $*" >&2; exit 1; } +if grep -Eq 'KERNEL_BACKPORT_|snapshot\.debian\.org|kernel-backports\.list' "$RECIPE/../build.sh"; then + fail 'bridge policy leaked into the parent recipe' +fi +[ "$(grep -Fc '"$SOURCE_DIR/kernel-backports/' "$RECIPE/../build.sh")" -eq 2 ] || fail 'expected two bridge hooks' +if grep -Eq '^KERNEL_(BACKPORT|DEB_ARCH)' "$RECIPE/../../../build.mk"; then + fail 'bridge build policy leaked into the parent Makefile' +fi +fixture() { + local package=$1 architecture=$2 compression=$3 + rm -rf "$WORK/input" + mkdir -p "$WORK/input/DEBIAN" "$WORK/input/boot" + printf 'signed-kernel-payload\000keep-unchanged\377\n' > "$WORK/input/boot/vmlinuz-test" + if [[ "$package" = linux-headers-* ]]; then + mkdir -p "$WORK/input/usr/src/kernel-test" + printf 'CC = $(CROSS_COMPILE)gcc-16\noverride KERNELRELEASE = test-abi\n' \ + > "$WORK/input/usr/src/kernel-test/.kernelvariables" + mkdir -p "$WORK/input/usr/lib/modules/test-abi" + ln -s ../../../src/kernel-test "$WORK/input/usr/lib/modules/test-abi/build" + printf 'CONFIG_GCC_VERSION=160200\n' > "$WORK/input/usr/src/kernel-test/.config" + (cd "$WORK/input" && md5sum usr/src/kernel-test/.kernelvariables usr/src/kernel-test/.config > DEBIAN/md5sums) + fi + cat > "$WORK/input/DEBIAN/control" < +Source: linux ($KERNEL_BACKPORT_UPSTREAM_VERSION) +Built-Using: linux (= $KERNEL_BACKPORT_UPSTREAM_VERSION) +Depends: linux-base-test (= $KERNEL_BACKPORT_UPSTREAM_VERSION), + gcc-16-for-host, libc6 (>= 2.38) +Breaks: linux-base-old (<< $KERNEL_BACKPORT_UPSTREAM_VERSION~) +Description: test payload $KERNEL_BACKPORT_UPSTREAM_VERSION gcc-16-for-host +EOF + dpkg-deb --root-owner-group -Z"$compression" --build "$WORK/input" "$WORK/source.deb" >/dev/null +} + +for fixture_case in 'linux-image-test amd64 xz' 'linux-headers-test all gzip'; do + read -r package architecture compression <<< "$fixture_case" + fixture "$package" "$architecture" "$compression" + "$RECIPE/repack-kernel-deb.sh" "$WORK/source.deb" "$WORK/output" >/dev/null + deb="$WORK/output/${package}_${KERNEL_BACKPORT_VERSION}_${architecture}.deb" + [ "$(dpkg-deb -f "$deb" Version)" = "$KERNEL_BACKPORT_VERSION" ] || fail version + [ "$(dpkg-deb -f "$deb" Source)" = "linux ($KERNEL_BACKPORT_UPSTREAM_VERSION)" ] || fail source + [ "$(dpkg-deb -f "$deb" Built-Using)" = "linux (= $KERNEL_BACKPORT_UPSTREAM_VERSION)" ] || fail provenance + [ "$(dpkg-deb -f "$deb" Original-Maintainer)" = 'Debian Kernel Team ' ] || fail attribution + [ "$(dpkg-deb -f "$deb" X-Start9-Upstream-SHA256)" = "$(sha256sum "$WORK/source.deb" | cut -d' ' -f1)" ] || fail commitment + dpkg-deb -f "$deb" Depends | grep -Fq "linux-base-test (= $KERNEL_BACKPORT_VERSION)" || fail dependency + dpkg-deb -f "$deb" Depends | grep -Fq "$KERNEL_BACKPORT_COMPILER" || fail compiler + dpkg-deb -f "$deb" Breaks | grep -Fq "<< $KERNEL_BACKPORT_VERSION~" || fail breaks + dpkg-deb -f "$deb" Description | grep -Fq "$KERNEL_BACKPORT_UPSTREAM_VERSION gcc-16-for-host" || fail description + rm -rf "$WORK/inspect" "$WORK/inspect-control" + dpkg-deb --extract "$deb" "$WORK/inspect" + cmp "$WORK/input/boot/vmlinuz-test" "$WORK/inspect/boot/vmlinuz-test" || fail kernel-bytes + if [[ "$package" = linux-headers-* ]]; then + grep -Fxq "CC = \$(CROSS_COMPILE)${KERNEL_BACKPORT_COMPILER%-for-host}" \ + "$WORK/inspect/usr/src/kernel-test/.kernelvariables" || fail compiler-selector + grep -Fxq 'override KERNELRELEASE = test-abi' \ + "$WORK/inspect/usr/src/kernel-test/.kernelvariables" || fail abi + cmp "$WORK/input/usr/src/kernel-test/.config" "$WORK/inspect/usr/src/kernel-test/.config" || fail kernel-config + dpkg-deb --control "$deb" "$WORK/inspect-control" + (cd "$WORK/inspect" && md5sum -c "$WORK/inspect-control/md5sums") || fail header-checksum + else + data=$(ar t "$WORK/source.deb" | grep '^data\.tar') + cmp <(ar p "$WORK/source.deb" "$data") <(ar p "$deb" "$data") || fail payload + fi + cp "$deb" "$WORK/first.deb" + sleep 1 + "$RECIPE/repack-kernel-deb.sh" "$WORK/source.deb" "$WORK/output" >/dev/null + cmp "$WORK/first.deb" "$deb" || fail reproducibility +done + +dpkg --compare-versions "$KERNEL_BACKPORT_VERSION" lt "$KERNEL_BACKPORT_UPSTREAM_VERSION~bpo13+1" || fail official-order +sed -i 's/^Version:.*/Version: 1.0/' "$WORK/input/DEBIAN/control" +dpkg-deb --root-owner-group --build "$WORK/input" "$WORK/wrong.deb" >/dev/null +if "$RECIPE/repack-kernel-deb.sh" "$WORK/wrong.deb" "$WORK/output" >/dev/null 2>&1; then + fail 'unmatched source version accepted' +fi + +mkdir -p "$WORK/recipe" "$WORK/stage/config/archives" +cp "$RECIPE/kernel-backports.conf" "$RECIPE/stage.sh" "$WORK/recipe/" +cat > "$WORK/recipe/build-kernel-backports.sh" <<'EOF' +#!/bin/bash +printf '%s\n' "$@" > "$RESULTS_DIR/called" +EOF +chmod +x "$WORK/recipe/build-kernel-backports.sh" +export SOURCE_DIR="$WORK/recipe" RESULTS_DIR="$WORK" +cd "$WORK/stage" +for target in x86_64:amd64 x86_64-nonfree:amd64 x86_64-nvidia:amd64 aarch64:arm64 aarch64-nonfree:arm64 aarch64-nvidia:arm64; do + IFS=: read -r platform arch <<< "$target" + rm -f config/archives/kernel-backports.list.chroot "$WORK/called" + bash "$WORK/recipe/stage.sh" trixie "$platform" "$arch" "$RESULTS_DIR" + [ -f "$WORK/called" ] || fail "$platform archive build" + grep -Fxq "deb [trusted=yes] file://$WORK/kernel-backports/$arch/$KERNEL_BACKPORT_VERSION ./" \ + config/archives/kernel-backports.list.chroot || fail "$platform archive URL" +done +for target in raspberrypi:arm64 rockchip64:arm64 riscv64:riscv64 riscv64-nonfree:riscv64; do + IFS=: read -r platform arch <<< "$target" + rm -f config/archives/kernel-backports.list.chroot "$WORK/called" + bash "$WORK/recipe/stage.sh" trixie "$platform" "$arch" "$RESULTS_DIR" + [ ! -f "$WORK/called" ] || fail "$platform kernel selection changed" + [ ! -f config/archives/kernel-backports.list.chroot ] || fail "$platform retained bridge archive" +done +rm -f "$WORK/called" +bash "$WORK/recipe/stage.sh" bookworm x86_64 amd64 "$RESULTS_DIR" +[ ! -f "$WORK/called" ] || fail 'bridge used outside trixie' + +"$RECIPE/verify-kernel-backports.sh" "$WORK/not-an-image" amd64 +: > "$KERNEL_BACKPORT_ARCHIVE_LIST" +IMAGE="$WORK/image" +ABI=7.3.4+deb13-amd64 +mkdir -p "$IMAGE"/{var/lib/dpkg,usr/lib/modules/$ABI,boot,etc/default} +cat > "$IMAGE/var/lib/dpkg/status" < +Description: official backport fixture +EOF +printf 'selected-kernel' > "$IMAGE/usr/lib/modules/$ABI/vmlinuz" +cp "$IMAGE/usr/lib/modules/$ABI/vmlinuz" "$IMAGE/boot/vmlinuz-$ABI" +printf 'retained-kernel' > "$IMAGE/boot/vmlinuz-7.3.4+deb14-amd64" +printf 'GRUB_TOP_LEVEL="/boot/vmlinuz-%s"\n' "$ABI" > "$IMAGE/etc/default/grub" +"$RECIPE/verify-kernel-backports.sh" "$IMAGE" amd64 +printf 'GRUB_TOP_LEVEL="/boot/vmlinuz-7.3.4+deb14-amd64"\n' > "$IMAGE/etc/default/grub" +if "$RECIPE/verify-kernel-backports.sh" "$IMAGE" amd64 >/dev/null 2>&1; then + fail 'retained higher ABI selected' +fi +printf 'GRUB_TOP_LEVEL="/boot/vmlinuz-%s"\n' "$ABI" > "$IMAGE/etc/default/grub" +printf 'wrong-kernel' > "$IMAGE/boot/vmlinuz-$ABI" +if "$RECIPE/verify-kernel-backports.sh" "$IMAGE" amd64 >/dev/null 2>&1; then + fail 'mismatched boot binary accepted' +fi +cp "$IMAGE/usr/lib/modules/$ABI/vmlinuz" "$IMAGE/boot/vmlinuz-$ABI" +sed -i 's/^Version:.*/Version: 7.2.12-1~bpo13+1/' "$IMAGE/var/lib/dpkg/status" +if "$RECIPE/verify-kernel-backports.sh" "$IMAGE" amd64 >/dev/null 2>&1; then + fail 'old kernel package accepted' +fi +printf 'kernel backports tests passed\n' diff --git a/projects/start-os/build/image-recipe/kernel-backports/verify-kernel-backports.sh b/projects/start-os/build/image-recipe/kernel-backports/verify-kernel-backports.sh new file mode 100755 index 0000000000..77baaec544 --- /dev/null +++ b/projects/start-os/build/image-recipe/kernel-backports/verify-kernel-backports.sh @@ -0,0 +1,17 @@ +#!/bin/bash +set -euo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/kernel-backports.conf" +[ -f "$KERNEL_BACKPORT_ARCHIVE_LIST" ] || exit 0 +ROOT=$(realpath "$1") +ARCH=$2 +VERSION=$(dpkg-query --admindir="$ROOT/var/lib/dpkg" -W -f='${Version}' "linux-image-$ARCH") +dpkg --compare-versions "$VERSION" ge "$KERNEL_BACKPORT_VERSION" +mapfile -t BINARIES < <(find "$ROOT/usr/lib/modules" -mindepth 2 -maxdepth 2 -name vmlinuz -type f) +if [ "${#BINARIES[@]}" -ne 1 ]; then + echo 'Expected one image-selected kernel binary' >&2 + exit 1 +fi +KVER=$(basename "$(dirname "${BINARIES[0]}")") +cmp "${BINARIES[0]}" "$ROOT/boot/vmlinuz-$KVER" +grep -Fxq "GRUB_TOP_LEVEL=\"/boot/vmlinuz-$KVER\"" "$ROOT/etc/default/grub" +printf 'Verified image kernel %s, package %s\n' "$KVER" "$VERSION" diff --git a/projects/start-os/build/tests/backports-pref-test.sh b/projects/start-os/build/tests/backports-pref-test.sh index e15fd2afc4..ecccc31fa0 100755 --- a/projects/start-os/build/tests/backports-pref-test.sh +++ b/projects/start-os/build/tests/backports-pref-test.sh @@ -27,7 +27,7 @@ cd "$TMP" for IB_SUITE in trixie bookworm; do export IB_SUITE cat > "$TMP/expected" < "$WORK/kbuild.sh" +mkdir "$WORK/bin" +cat > "$WORK/bin/ls" <<'EOF' +#!/bin/bash +printf '/boot/vmlinuz-target-abi\n' +EOF +cat > "$WORK/bin/apt-cache" <<'EOF' +#!/bin/bash +[ "$*" = 'depends linux-headers-target-abi' ] || exit 1 +printf ' Depends: linux-kbuild-from-header-metadata\n' +EOF +cat > "$WORK/bin/apt-get" <<'EOF' +#!/bin/bash +printf '%s\n' "$*" > "$RESULTS_DIR/kbuild-installed" +EOF +chmod +x "$WORK/bin/"* +RESULTS_DIR="$WORK" PATH="$WORK/bin:$PATH" bash "$WORK/kbuild.sh" +grep -Fxq 'install -y linux-kbuild-from-header-metadata' "$WORK/kbuild-installed" +printf 'target kbuild selection test passed\n' diff --git a/projects/start-os/changelog/patch-security-kernel-backports.md b/projects/start-os/changelog/patch-security-kernel-backports.md new file mode 100644 index 0000000000..5a07d93c5e --- /dev/null +++ b/projects/start-os/changelog/patch-security-kernel-backports.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Fix Linux networking vulnerabilities CVE-2026-99284 and CVE-2026-99288 on x86 and generic ARM servers by updating to Debian-signed Linux 7.3.4. diff --git a/projects/start-os/changelog/patch-security-pi-tcp-kernel.md b/projects/start-os/changelog/patch-security-pi-tcp-kernel.md new file mode 100644 index 0000000000..4c09e36eab --- /dev/null +++ b/projects/start-os/changelog/patch-security-pi-tcp-kernel.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Update the Raspberry Pi kernel to fix CVE-2026-98432, a flaw in TCP connection handling. diff --git a/projects/start-os/debian/postinst b/projects/start-os/debian/postinst index 9248c679c1..7fb9b021a8 100755 --- a/projects/start-os/debian/postinst +++ b/projects/start-os/debian/postinst @@ -44,6 +44,7 @@ if [ -f /etc/default/grub ]; then mkdir -p /etc/default/grub.d cp /usr/lib/startos/grub-user.cfg /etc/default/grub.d/zz-startos-user.cfg grub_set GRUB_DISTRIBUTOR "StartOS v$(cat /usr/lib/startos/VERSION.txt)" + # Image-built defaults must select their kernel across lower-ABI updates. grub_set GRUB_TOP_LEVEL "$(ls -1 /boot/vmlinuz-* | sort -V | tail -n1)" # Graphical terminal (serial added conditionally via /etc/grub.d/01_serial) grub_set GRUB_TERMINAL_INPUT 'console' diff --git a/projects/start-wrt/AGENTS.md b/projects/start-wrt/AGENTS.md index ec9f6136c0..3c1f13d363 100644 --- a/projects/start-wrt/AGENTS.md +++ b/projects/start-wrt/AGENTS.md @@ -298,6 +298,12 @@ and retain their selected `PROFILE`. | `make start-wrt-update STARTWRT_REMOTE=root@IP` | deploy binary over SSH (default `root@192.168.0.1`) | | `make start-wrt-clean` | remove start-wrt build artifacts | +`make start-wrt-ca-test` checks the built image's certificate stores: they must exclude +emSign ECC Root CA - G3 and keep ISRG Root X1. It needs a completed `make start-wrt-image` +and OpenSSL; image CI runs it after the build. A failed incremental build can leave the +previous rootfs; the check verifies its certificates, not image freshness. +`STARTWRT_CA_ROOTFS` selects an unpacked image root for artifact verification. + The OpenWrt image build needs a consistent environment — Docker is recommended; native builds on some distros fail silently. @@ -356,7 +362,7 @@ rebuilds. Every setup run: 3. Rsyncs [`openwrt-overlay/`](openwrt-overlay/) over the tree — the _added_ files (mirroring upstream layout): `target/linux/spacemit/` (the K1 target, including its `patches-6.18/` kernel patches), `package/boot/{opensbi,uboot}-spacemit/`, the generic - 6.18 kernel stubs, one mac80211 build patch, and a wireless-regdb patch. Additions live as plain files, not + 6.18 kernel stubs, one mac80211 build patch, a wireless-regdb patch, and a ca-certificates patch. Additions live as plain files, not patches, so upstream bumps can never conflict with them. Most of this tree comes from SpaceMiT's BSP and from OpenWrt, and it is GPL-2.0-only rather than MIT — see [`openwrt-overlay/README.md`](openwrt-overlay/README.md) before editing it. diff --git a/projects/start-wrt/build.mk b/projects/start-wrt/build.mk index cbc23e9e27..5963ec63b5 100644 --- a/projects/start-wrt/build.mk +++ b/projects/start-wrt/build.mk @@ -99,13 +99,7 @@ $(STARTWRT_WEB_CONFIG): $(STARTWRT_GIT_HASH_FILE) $(STARTWRT_DIR)/web/config-sam start-wrt-test: $(STARTWRT_RUST_SRC) $(ENVIRONMENT_FILE) ./$(STARTWRT_DIR)/build/run-tests.sh -# --- OpenWrt image (HEAVY) --- -# Tree prep + feeds/config/download. openwrt/ is a disposable, gitignored -# build workspace (no submodule, no git repo inside): openwrt-setup.sh rebuilds -# it from the sha256-pinned upstream release tarball (build/openwrt-version), -# applies the Start9 delta (openwrt-patches/ + openwrt-overlay/), then runs -# feeds/config/download. Re-runs whenever the pin, patches, overlay, feeds, or -# diffconfig change. +# Setup rebuilds pinned sources while preserving generated build state. .PHONY: start-wrt-openwrt-setup start-wrt-openwrt-setup: $(STARTWRT_OPENWRT)/.config $(STARTWRT_OPENWRT)/.config: $(STARTWRT_DIR)/build/openwrt.diffconfig $(STARTWRT_DIR)/build/feeds.conf \ @@ -133,6 +127,10 @@ $(STARTWRT_IMAGES) &: $(STARTWRT_OPENWRT)/.config $(STARTWRT_OPENWRT)/files/.sta gzip -9nc $(STARTWRT_IMAGE_DIR)/$(STARTWRT_SDCARD_SRC) > results/$(STARTWRT_SDCARD_NAME) cp $(STARTWRT_IMAGE_DIR)/$(STARTWRT_SYSUPGRADE_SRC) results/$(STARTWRT_SYSUPGRADE_NAME) +.PHONY: start-wrt-ca-test +start-wrt-ca-test: + ./$(STARTWRT_DIR)/build/test-ca-certificates.sh + # Deploy binary + restart daemon over SSH (atomic temp -> sync -> rename). .PHONY: start-wrt-update start-wrt-update: $(STARTWRT_BIN) diff --git a/projects/start-wrt/build/gen-kernel-patch.sh b/projects/start-wrt/build/gen-kernel-patch.sh index 1fe6ad53bb..5817624750 100755 --- a/projects/start-wrt/build/gen-kernel-patch.sh +++ b/projects/start-wrt/build/gen-kernel-patch.sh @@ -7,7 +7,7 @@ set -euo pipefail VENDOR_URL=https://gitlab.com/jmontleon/kernel-ark.git -VENDOR_REF=b9f88a74901a71a6bdf666c90d86ee7027f56b7d +VENDOR_REF=421ac7d4996cadeef8a6df5d867e008adfcadd6f STABLE_URL=https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git # Fedora ARK packaging and patches the vendor tree carries beside the K1 work. diff --git a/projects/start-wrt/build/test-ca-certificates.sh b/projects/start-wrt/build/test-ca-certificates.sh new file mode 100755 index 0000000000..2f31961d9e --- /dev/null +++ b/projects/start-wrt/build/test-ca-certificates.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT=$(git rev-parse --show-toplevel) +shopt -s nullglob +if [ -n "${STARTWRT_CA_ROOTFS:-}" ]; then + ROOTFS=("$STARTWRT_CA_ROOTFS") +else + # A retained rootfs can belong to an earlier successful build. + ROOTFS=("$ROOT"/projects/start-wrt/openwrt/build_dir/target-*/root-*) +fi +[ "${#ROOTFS[@]}" -eq 1 ] && [ -d "${ROOTFS[0]}" ] || { + echo 'Build the StartWRT image or set STARTWRT_CA_ROOTFS to its unpacked root.' >&2 + exit 1 +} +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT + +find "${ROOTFS[0]}/etc/ssl/certs" -type f -exec cat {} + > "$TMP/trust.pem" +openssl crl2pkcs7 -nocrl -certfile "$TMP/trust.pem" | + openssl pkcs7 -print_certs -noout > "$TMP/subjects" + +if grep -Eq '^subject=(.*, ?)?CN ?= ?emSign ECC Root CA - G3(,|$)' "$TMP/subjects"; then + echo 'The image trust store still includes emSign ECC Root CA - G3.' >&2 + exit 1 +fi +grep -Eq '^subject=(.*, ?)?CN ?= ?ISRG Root X1(,|$)' "$TMP/subjects" || { + echo 'The image trust store is missing ISRG Root X1.' >&2 + exit 1 +} +printf 'The image trust store excludes emSign ECC Root CA - G3 and keeps unrelated roots.\n' diff --git a/projects/start-wrt/changelog/patch-security-kernel-and-certificate-trust.md b/projects/start-wrt/changelog/patch-security-kernel-and-certificate-trust.md new file mode 100644 index 0000000000..322420744b --- /dev/null +++ b/projects/start-wrt/changelog/patch-security-kernel-and-certificate-trust.md @@ -0,0 +1,6 @@ +--- +release-notes: false +--- + +- Update the router kernel to fix CVE-2026-99284 and CVE-2026-99288 (NoisyTCP), which can allow local takeover or a remotely triggered crash. +- Stop trusting the emSign ECC Root CA - G3 certificate authority, which browsers distrusted after keys for intermediate authorities it signed were compromised. diff --git a/projects/start-wrt/openwrt-overlay/README.md b/projects/start-wrt/openwrt-overlay/README.md index 0ae16ba153..a4e172c75c 100644 --- a/projects/start-wrt/openwrt-overlay/README.md +++ b/projects/start-wrt/openwrt-overlay/README.md @@ -20,6 +20,7 @@ Most of it comes from SpaceMiT's OpenWrt BSP and from OpenWrt itself: | `target/linux/spacemit/patches-6.18/*` | SpaceMiT Ltd. and the respective Linux kernel contributors | | `package/kernel/mac80211/patches/`, `package/boot/uboot-spacemit/patches/` | The respective OpenWrt and U-Boot contributors | | `package/firmware/wireless-regdb/patches/` | The wireless-regdb contributors (ISC) | +| `package/system/ca-certificates/patches/` | The Debian ca-certificates contributors | Sixteen files carry an explicit `SPDX-License-Identifier: GPL-2.0-only` header, most of them naming a copyright holder. The `.patch` files are diffs against diff --git a/projects/start-wrt/openwrt-overlay/package/system/ca-certificates/patches/0002-blacklist-certs.patch b/projects/start-wrt/openwrt-overlay/package/system/ca-certificates/patches/0002-blacklist-certs.patch new file mode 100644 index 0000000000..74b34a6db8 --- /dev/null +++ b/projects/start-wrt/openwrt-overlay/package/system/ca-certificates/patches/0002-blacklist-certs.patch @@ -0,0 +1,24 @@ +From 4a0203e5ce4ce1a064b97387f52ca6a00c97185c Mon Sep 17 00:00:00 2001 +From: Salvatore Bonaccorso +Date: Tue, 20 Oct 2026 16:39:15 +0200 +Subject: [PATCH] Blacklist "emSign ECC Root CA - G3" and "Comodo AAA Services + root" + +Closes: #1151413 +Source: https://salsa.debian.org/debian/ca-certificates/-/commit/4a0203e5ce4ce1a064b97387f52ca6a00c97185c +--- + mozilla/blacklist.txt | 5 +++++ + 1 file changed, 5 insertions(+) + +--- a/mozilla/blacklist.txt ++++ b/mozilla/blacklist.txt +@@ -3,4 +3,9 @@ + # Blacklist explicitly distrusted certificates to explicitly ignore them and prevent build errors + "Explicitly Distrust DigiNotar Root CA" + ++# Blacklist "emSign ECC Root CA - G3" (cf. #1151413) ++"emSign ECC Root CA - G3" ++# Blacklist "Comodo AAA Services root" (cf. #1151413) ++"Comodo AAA Services root" ++ + # Expired CAs diff --git a/projects/start-wrt/openwrt-overlay/target/linux/generic/kernel-6.18 b/projects/start-wrt/openwrt-overlay/target/linux/generic/kernel-6.18 index f95022dd49..82b30ac327 100644 --- a/projects/start-wrt/openwrt-overlay/target/linux/generic/kernel-6.18 +++ b/projects/start-wrt/openwrt-overlay/target/linux/generic/kernel-6.18 @@ -1,2 +1,2 @@ -LINUX_VERSION-6.18 = .57 -LINUX_KERNEL_HASH-6.18.57 = 5bd9acdc82ec5efc3790ae840e5aaa40dfde7efff261cf6dde902dc570acf98c +LINUX_VERSION-6.18 = .64 +LINUX_KERNEL_HASH-6.18.64 = 020d45510c539972e6f14c5c71566878d3b7ef56fb082b3e09134f2ebaade562 diff --git a/projects/start-wrt/openwrt-overlay/target/linux/spacemit/patches-6.18/0000-spacemit-k1-vendor-kernel.patch b/projects/start-wrt/openwrt-overlay/target/linux/spacemit/patches-6.18/0000-spacemit-k1-vendor-kernel.patch index 45899a73d8..7e7b0a711d 100644 --- a/projects/start-wrt/openwrt-overlay/target/linux/spacemit/patches-6.18/0000-spacemit-k1-vendor-kernel.patch +++ b/projects/start-wrt/openwrt-overlay/target/linux/spacemit/patches-6.18/0000-spacemit-k1-vendor-kernel.patch @@ -1,7 +1,7 @@ Subject: spacemit: SpaceMiT K1 vendor kernel -The https://gitlab.com/jmontleon/kernel-ark.git tree at b9f88a74901a71a6bdf666c90d86ee7027f56b7d, -as a diff against mainline v6.18.57, without its Fedora packaging and +The https://gitlab.com/jmontleon/kernel-ark.git tree at 421ac7d4996cadeef8a6df5d867e008adfcadd6f, +as a diff against mainline v6.18.64, without its Fedora packaging and patches or these vendor drivers: drivers/gpu/drm/img-rogue @@ -37157,7 +37157,7 @@ index 795b2e815ac9..d92de11b8f74 100644 return 0; } diff --git a/arch/riscv/kernel/traps.c b/arch/riscv/kernel/traps.c -index 47afea4ff1a8..ee711131623c 100644 +index e7e45cbb0899..b7745880f672 100644 --- a/arch/riscv/kernel/traps.c +++ b/arch/riscv/kernel/traps.c @@ -170,12 +170,39 @@ DO_ERROR_INFO(do_trap_insn_misaligned, @@ -37251,7 +37251,7 @@ index 557bf160b503..1896a756ef94 100644 hugetlb_cma_reserve(PUD_SHIFT - PAGE_SHIFT); } diff --git a/block/blk-mq.c b/block/blk-mq.c -index ba0c48d58e13..26db01994089 100644 +index 82df2f6073d8..1f4066c992fe 100644 --- a/block/blk-mq.c +++ b/block/blk-mq.c @@ -1316,6 +1316,7 @@ static void blk_mq_complete_send_ipi(struct request *rq) @@ -37262,7 +37262,7 @@ index ba0c48d58e13..26db01994089 100644 } static void blk_mq_raise_softirq(struct request *rq) -@@ -3603,6 +3604,7 @@ static int blk_mq_init_request(struct blk_mq_tag_set *set, struct request *rq, +@@ -3605,6 +3606,7 @@ static int blk_mq_init_request(struct blk_mq_tag_set *set, struct request *rq, } WRITE_ONCE(rq->state, MQ_RQ_IDLE); @@ -37284,7 +37284,7 @@ index f6fa4d8d75e0..6d70e323eb8c 100644 $(obj)/signing_key.pem: $(obj)/x509.genkey FORCE $(call if_changed,gen_key) diff --git a/drivers/ata/libata-pmp.c b/drivers/ata/libata-pmp.c -index 299b1823e0d0..6d7a4e9453ad 100644 +index c3b3af28d17c..e9b743bd5fea 100644 --- a/drivers/ata/libata-pmp.c +++ b/drivers/ata/libata-pmp.c @@ -458,7 +458,8 @@ static void sata_pmp_quirks(struct ata_port *ap) @@ -44487,10 +44487,10 @@ index cfc4d83c42c0..339b2cac3442 100644 error = cpuhp_setup_state(CPUHP_AP_RISCV_TIMER_STARTING, "clockevents/riscv/timer:starting", diff --git a/drivers/cpufreq/Kconfig b/drivers/cpufreq/Kconfig -index 78702a08364f..c78240439d9b 100644 +index 73c1b62c1b37..0d46d3e2d200 100644 --- a/drivers/cpufreq/Kconfig +++ b/drivers/cpufreq/Kconfig -@@ -337,6 +337,15 @@ config QORIQ_CPUFREQ +@@ -338,6 +338,15 @@ config QORIQ_CPUFREQ This adds the CPUFreq driver support for Freescale QorIQ SoCs which are capable of changing the CPU's frequency dynamically. @@ -48787,7 +48787,7 @@ index 000000000000..90b3c46343e8 +}; +module_rpmsg_driver(rpmsg_adma_client); diff --git a/drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c b/drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c -index ea4e47ee0d71..8a0d89aaf4b0 100644 +index 343d32eeaa29..9059c39319e9 100644 --- a/drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c +++ b/drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c @@ -48,7 +48,7 @@ @@ -76099,7 +76099,7 @@ index 000000000000..1094d1759c5b +MODULE_DESCRIPTION("SPACEMIT adc driver"); +MODULE_LICENSE("GPL v2"); diff --git a/drivers/iio/light/stk3310.c b/drivers/iio/light/stk3310.c -index 3be693421886..2ebb9eb1df0b 100644 +index ca1cb5dd776a..4cbd21ff1c65 100644 --- a/drivers/iio/light/stk3310.c +++ b/drivers/iio/light/stk3310.c @@ -16,6 +16,7 @@ @@ -116688,10 +116688,10 @@ index 000000000000..43b7a6c150d5 +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Spacemit"); diff --git a/drivers/mfd/Kconfig b/drivers/mfd/Kconfig -index 55a9fea95195..edcdfacbcfde 100644 +index ae39cbf31710..5fff341e0838 100644 --- a/drivers/mfd/Kconfig +++ b/drivers/mfd/Kconfig -@@ -2393,6 +2393,16 @@ config MFD_QCOM_PM8008 +@@ -2395,6 +2395,16 @@ config MFD_QCOM_PM8008 under it in the device tree. Additional drivers must be enabled in order to use the functionality of the device. @@ -121477,10 +121477,10 @@ index 5dd9c35f6b6f..cd9320cda798 100644 obj-$(CONFIG_MTD_SPI_NOR) += spi-nor.o diff --git a/drivers/mtd/spi-nor/core.c b/drivers/mtd/spi-nor/core.c -index 037407fc2e11..e801d08bab46 100644 +index 512d0e4e3b1f..0a4719e14dc6 100644 --- a/drivers/mtd/spi-nor/core.c +++ b/drivers/mtd/spi-nor/core.c -@@ -1954,6 +1954,7 @@ static const struct spi_nor_manufacturer *manufacturers[] = { +@@ -1963,6 +1963,7 @@ static const struct spi_nor_manufacturer *manufacturers[] = { &spi_nor_sst, &spi_nor_winbond, &spi_nor_xmc, @@ -147341,7 +147341,7 @@ index ab25419f56c6..4f46f8235580 100644 obj-$(CONFIG_RTW89) += rtw89/ - diff --git a/drivers/nvme/host/pci.c b/drivers/nvme/host/pci.c -index 4efb55f1e383..152800ceb785 100644 +index 9245fae71321..8ef7e5fa106f 100644 --- a/drivers/nvme/host/pci.c +++ b/drivers/nvme/host/pci.c @@ -2350,7 +2350,7 @@ static void nvme_free_host_mem_multi(struct nvme_dev *dev) @@ -147591,7 +147591,7 @@ index 000000000000..282ecc8977c3 +MODULE_LICENSE("GPL v2"); + diff --git a/drivers/opp/core.c b/drivers/opp/core.c -index a179d57a5a15..9065b256f3d0 100644 +index fc2a7ee936ba..61e6c6361791 100644 --- a/drivers/opp/core.c +++ b/drivers/opp/core.c @@ -763,8 +763,13 @@ EXPORT_SYMBOL_GPL(dev_pm_opp_find_freq_exact_indexed); @@ -147620,7 +147620,7 @@ index a179d57a5a15..9065b256f3d0 100644 } EXPORT_SYMBOL_GPL(dev_pm_opp_find_freq_ceil); -@@ -2641,6 +2650,111 @@ int dev_pm_opp_set_config(struct device *dev, struct dev_pm_opp_config *config) +@@ -2637,6 +2646,111 @@ int dev_pm_opp_set_config(struct device *dev, struct dev_pm_opp_config *config) } EXPORT_SYMBOL_GPL(dev_pm_opp_set_config); @@ -147807,10 +147807,10 @@ index 48e4a887bb1b..d969d690a77f 100644 msi_vaddr = dmam_alloc_coherent(dev, sizeof(u64), &pp->msi_data, GFP_KERNEL); diff --git a/drivers/pci/controller/dwc/pcie-designware.h b/drivers/pci/controller/dwc/pcie-designware.h -index aa27211b68dd..19ffc62a585a 100644 +index c01634c0211f..3842211c90e5 100644 --- a/drivers/pci/controller/dwc/pcie-designware.h +++ b/drivers/pci/controller/dwc/pcie-designware.h -@@ -422,6 +422,7 @@ struct dw_pcie_rp { +@@ -423,6 +423,7 @@ struct dw_pcie_rp { const struct dw_pcie_host_ops *ops; int msi_irq[MAX_MSI_CTRLS]; struct irq_domain *irq_domain; @@ -152776,7 +152776,7 @@ index 000000000000..82203d02aa47 +MODULE_DESCRIPTION("CW2015 FGADC Device Driver V3.0"); +MODULE_LICENSE("GPL"); diff --git a/drivers/power/supply/sbs-battery.c b/drivers/power/supply/sbs-battery.c -index 3947429f6f81..8c1d1bd90afc 100644 +index b190a4a89952..73a6ab4272d1 100644 --- a/drivers/power/supply/sbs-battery.c +++ b/drivers/power/supply/sbs-battery.c @@ -609,6 +609,21 @@ static int sbs_get_battery_presence_and_health( @@ -184298,10 +184298,10 @@ index 074d9c731639..3877e39170c2 100644 */ of_match = of_match_device(pdev->dev.driver->of_match_table, &pdev->dev); diff --git a/drivers/usb/host/xhci.c b/drivers/usb/host/xhci.c -index 14eeb16f668b..177f3e4e5d3d 100644 +index b894ba988a3d..3c815435bf51 100644 --- a/drivers/usb/host/xhci.c +++ b/drivers/usb/host/xhci.c -@@ -5535,6 +5535,10 @@ int xhci_gen_setup(struct usb_hcd *hcd, xhci_get_quirks_t get_quirks) +@@ -5536,6 +5536,10 @@ int xhci_gen_setup(struct usb_hcd *hcd, xhci_get_quirks_t get_quirks) xhci_dbg(xhci, "Enabling %u-bit DMA addresses.\n", xhci->dma_mask_bits); dma_set_coherent_mask(dev, DMA_BIT_MASK(xhci->dma_mask_bits)); @@ -184312,7 +184312,7 @@ index 14eeb16f668b..177f3e4e5d3d 100644 } else { /* * This is to avoid error in cases where a 32-bit USB -@@ -5547,6 +5551,12 @@ int xhci_gen_setup(struct usb_hcd *hcd, xhci_get_quirks_t get_quirks) +@@ -5548,6 +5552,12 @@ int xhci_gen_setup(struct usb_hcd *hcd, xhci_get_quirks_t get_quirks) dma_set_coherent_mask(dev, DMA_BIT_MASK(32)); } @@ -188190,7 +188190,7 @@ index 000000000000..c854ab926e52 +MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR); +MODULE_ALIAS("platform:soc-wdt"); diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c -index d66681ce2b3d..90265b7ad206 100644 +index 204edb659304..3410e98c3786 100644 --- a/fs/btrfs/sysfs.c +++ b/fs/btrfs/sysfs.c @@ -655,7 +655,7 @@ static const struct attribute_group btrfs_debug_feature_attr_group = { @@ -192541,10 +192541,10 @@ index 91fe08b7e886..8e9969a00cf2 100644 return NULL; diff --git a/net/wireless/reg.c b/net/wireless/reg.c -index 15e56dfad00f..848e17e9ed80 100644 +index 3f685b1396ff..8f6358c06df6 100644 --- a/net/wireless/reg.c +++ b/net/wireless/reg.c -@@ -1008,7 +1008,7 @@ static void regdb_fw_cb(const struct firmware *fw, void *context) +@@ -1011,7 +1011,7 @@ static void regdb_fw_cb(const struct firmware *fw, void *context) void *db; if (!fw) { diff --git a/projects/start-wrt/openwrt-patches/0011-ca-certificates-distrust-emsign-g3.patch b/projects/start-wrt/openwrt-patches/0011-ca-certificates-distrust-emsign-g3.patch new file mode 100644 index 0000000000..a6645131d8 --- /dev/null +++ b/projects/start-wrt/openwrt-patches/0011-ca-certificates-distrust-emsign-g3.patch @@ -0,0 +1,21 @@ +Subject: ca-certificates: blacklist "emSign ECC Root CA - G3" + +Backport of openwrt/openwrt 4a686570eb6495635279273f034caa2a0f37f36e +from openwrt-25.12, with its package patch in +openwrt-overlay/package/system/ca-certificates/patches/. Drop both once +the pinned release includes that commit. + +Start9 downstream patch (start-technologies projects/start-wrt). +Applies to: openwrt v25.12.6 + +--- a/package/system/ca-certificates/Makefile ++++ b/package/system/ca-certificates/Makefile +@@ -8,7 +8,7 @@ + + PKG_NAME:=ca-certificates + PKG_VERSION:=20260816 +-PKG_RELEASE:=1 ++PKG_RELEASE:=2 + PKG_MAINTAINER:= + + PKG_LICENSE:=GPL-2.0-or-later MPL-2.0 From 950c539cb56bd99ca0b8181bac165cc4a179d267 Mon Sep 17 00:00:00 2001 From: Helix the Red <355572797+helix-red@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:05:07 -0700 Subject: [PATCH 11/38] perf(squashfs): compress data blocks in parallel with byte-identical output (#4802) * perf(squashfs): compress data blocks in parallel with byte-identical output Data blocks are compressed on the blocking pool, one in flight per available CPU, and written in submission order. Block offsets and size words resolve from that order after the data section is written, so the image bytes do not depend on the worker count. The serial writer compressed every block inline on one async worker; large legacy-package conversions (0.3.6 migration) spent most of their time there on a Raspberry Pi 4. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * chore: changelog fragments for faster squashfs compression Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * perf(squashfs): queue data blocks on the rayon pool and reuse compression contexts A fixed rayon pool with four queued blocks per thread keeps every core busy past a slow head-of-line block without oversubscribing threads. Each thread reuses its Zstd context; ZSTD_compress2 resets the session per call, so frames are unchanged. A panicking job becomes a writer error instead of aborting the process. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --- Cargo.lock | 1 + .../patch-changed-package-packing-speed.md | 5 + .../patch-changed-package-conversion-speed.md | 5 + shared-libs/crates/start-core/Cargo.toml | 1 + .../start-core/src/util/squashfs/blocks.rs | 18 +- .../start-core/src/util/squashfs/write.rs | 195 +++++++++++++++--- .../src/util/squashfs/write/tests.rs | 58 ++++++ 7 files changed, 248 insertions(+), 35 deletions(-) create mode 100644 projects/start-cli/changelog/patch-changed-package-packing-speed.md create mode 100644 projects/start-os/changelog/patch-changed-package-conversion-speed.md diff --git a/Cargo.lock b/Cargo.lock index af82833993..b889133cff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8470,6 +8470,7 @@ dependencies = [ "qrcode", "r3bl_tui", "rand 0.10.3", + "rayon", "rcgen", "regex", "reqwest", diff --git a/projects/start-cli/changelog/patch-changed-package-packing-speed.md b/projects/start-cli/changelog/patch-changed-package-packing-speed.md new file mode 100644 index 0000000000..2a3b1aaba0 --- /dev/null +++ b/projects/start-cli/changelog/patch-changed-package-packing-speed.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Speed up service-package packing on multi-core systems. diff --git a/projects/start-os/changelog/patch-changed-package-conversion-speed.md b/projects/start-os/changelog/patch-changed-package-conversion-speed.md new file mode 100644 index 0000000000..d96a62789f --- /dev/null +++ b/projects/start-os/changelog/patch-changed-package-conversion-speed.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Speed up legacy service-package conversion on multi-core systems. diff --git a/shared-libs/crates/start-core/Cargo.toml b/shared-libs/crates/start-core/Cargo.toml index aec860646e..84aa5b5450 100644 --- a/shared-libs/crates/start-core/Cargo.toml +++ b/shared-libs/crates/start-core/Cargo.toml @@ -191,6 +191,7 @@ proptest-derive = "0.7.0" qrcode = "0.14.1" r3bl_tui = "0.7.6" rand = "0.10.1" +rayon = "1.12.0" rcgen = { version = "0.14", default-features = false, features = [ "pem", "ring", diff --git a/shared-libs/crates/start-core/src/util/squashfs/blocks.rs b/shared-libs/crates/start-core/src/util/squashfs/blocks.rs index 6dd93e2946..172cb9d5db 100644 --- a/shared-libs/crates/start-core/src/util/squashfs/blocks.rs +++ b/shared-libs/crates/start-core/src/util/squashfs/blocks.rs @@ -19,9 +19,25 @@ pub(super) struct EncodedBlock { pub compressed: bool, } +thread_local! { + static COMPRESSOR: std::cell::RefCell)>> = + const { std::cell::RefCell::new(None) }; +} + +/// Compresses with this thread's reusable context for the level. +fn compress(bytes: &[u8], level: i32) -> io::Result> { + COMPRESSOR.with_borrow_mut(|cached| { + if !matches!(cached, Some((cached_level, _)) if *cached_level == level) { + *cached = Some((level, zstd::bulk::Compressor::new(level)?)); + } + let (_, compressor) = cached.as_mut().expect("compressor initialized"); + compressor.compress(bytes) + }) +} + pub(super) fn encode_block(bytes: &[u8], level: i32) -> io::Result { // Known source size bounds the frame window to the kernel's block workspace. - let result = zstd::bulk::compress(bytes, level)?; + let result = compress(bytes, level)?; if result.len() >= bytes.len() { Ok(EncodedBlock { bytes: bytes.to_vec(), diff --git a/shared-libs/crates/start-core/src/util/squashfs/write.rs b/shared-libs/crates/start-core/src/util/squashfs/write.rs index dcec970919..ffd51ebe11 100644 --- a/shared-libs/crates/start-core/src/util/squashfs/write.rs +++ b/shared-libs/crates/start-core/src/util/squashfs/write.rs @@ -1,4 +1,4 @@ -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::ffi::OsString; use std::io::Write; use std::os::unix::ffi::OsStrExt; @@ -6,8 +6,11 @@ use std::path::PathBuf; use std::sync::Arc; use tokio::io::{AsyncReadExt, AsyncSeek, AsyncSeekExt, AsyncWrite, AsyncWriteExt}; +use tokio::sync::oneshot; -use super::blocks::{METADATA_SIZE, MetadataTable, UNCOMPRESSED_DATA, encode_block, invalid}; +use super::blocks::{ + EncodedBlock, METADATA_SIZE, MetadataTable, UNCOMPRESSED_DATA, encode_block, invalid, +}; use super::format::*; use super::tree::{normalize_path, *}; use crate::prelude::*; @@ -108,7 +111,6 @@ fn flatten(root: &Node) -> std::io::Result>> { .collect()) } -#[derive(Clone)] struct FileLayout { block: u64, size: u64, @@ -118,29 +120,129 @@ struct FileLayout { offset: u32, } +/// Data block position in output order. +type BlockIndex = usize; + +/// A file's layout before its compressed block sizes are known. +struct PendingLayout { + first: BlockIndex, + size: u64, + sparse: u64, + /// `None` for a sparse block. + blocks: Vec>, + fragment: u32, + offset: u32, +} + +/// Data blocks queued per compression thread. +const QUEUED_PER_THREAD: usize = 4; + +/// Compresses data blocks on the rayon pool and writes them in submission order. struct DataWriter { block_size: usize, level: i32, - fragments: Vec, + queue_depth: usize, + in_flight: VecDeque>>, + submitted: usize, + written: WrittenBlocks, + fragment_blocks: Vec, tail: Vec, } +struct WrittenBlocks { + start: u64, + ends: Vec, + sizes: Vec, +} + +impl WrittenBlocks { + fn position(&self, index: BlockIndex) -> u64 { + index + .checked_sub(1) + .map_or(self.start, |last| self.ends[last]) + } + + fn layout(&self, pending: &PendingLayout) -> FileLayout { + FileLayout { + block: self.position(pending.first), + size: pending.size, + sparse: pending.sparse, + blocks: pending + .blocks + .iter() + .map(|block| block.map_or(0, |index| self.sizes[index])) + .collect(), + fragment: pending.fragment, + offset: pending.offset, + } + } + + fn fragments(&self, blocks: &[BlockIndex]) -> Vec { + blocks + .iter() + .map(|index| Fragment { + block: self.position(*index), + size: self.sizes[*index], + unused: 0, + }) + .collect() + } +} + impl DataWriter { - fn new(options: Options) -> Self { + fn new(options: Options, queue_depth: usize, start: u64) -> Self { Self { block_size: options.block_size() as usize, level: options.compression_level(), - fragments: Vec::new(), + queue_depth: queue_depth.max(1), + in_flight: VecDeque::new(), + submitted: 0, + written: WrittenBlocks { + start, + ends: Vec::new(), + sizes: Vec::new(), + }, + fragment_blocks: Vec::new(), tail: Vec::new(), } } async fn block( - &self, - bytes: &[u8], + &mut self, + bytes: Vec, writer: &mut TrackingIO, - ) -> Result { - let block = encode_block(bytes, self.level)?; + ) -> Result { + if self.in_flight.len() >= self.queue_depth { + self.write_oldest(writer).await?; + } + let level = self.level; + let (send, receive) = oneshot::channel(); + rayon::spawn(move || { + // An unwinding rayon job aborts the process. + if let Ok(block) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + encode_block(&bytes, level) + })) { + let _ = send.send(block); + } + }); + self.in_flight.push_back(receive); + self.submitted += 1; + Ok(self.submitted - 1) + } + + async fn write_oldest( + &mut self, + writer: &mut TrackingIO, + ) -> Result<(), Error> { + let Some(task) = self.in_flight.pop_front() else { + return Ok(()); + }; + let block = task.await.map_err(|_| { + Error::new( + eyre!("SquashFS block compression stopped"), + ErrorKind::Unknown, + ) + })??; let size = u32::try_from(block.bytes.len()) .map_err(|_| invalid("SquashFS data block exceeds format limit"))? | if block.compressed { @@ -149,7 +251,9 @@ impl DataWriter { UNCOMPRESSED_DATA }; writer.write_all(&block.bytes).await?; - Ok(size) + self.written.sizes.push(size); + self.written.ends.push(writer.position()); + Ok(()) } async fn flush_fragment( @@ -157,29 +261,37 @@ impl DataWriter { writer: &mut TrackingIO, ) -> Result<(), Error> { if !self.tail.is_empty() { - let block = writer.position(); - let size = self.block(&self.tail, writer).await?; - self.fragments.push(Fragment { - block, - size, - unused: 0, - }); - self.tail.clear(); + let tail = std::mem::take(&mut self.tail); + let index = self.block(tail, writer).await?; + self.fragment_blocks.push(index); } Ok(()) } + /// Writes every outstanding block, including the final fragment. + async fn finish( + mut self, + writer: &mut TrackingIO, + ) -> Result<(WrittenBlocks, Vec), Error> { + self.flush_fragment(writer).await?; + while !self.in_flight.is_empty() { + self.write_oldest(writer).await?; + } + let fragments = self.written.fragments(&self.fragment_blocks); + Ok((self.written, fragments)) + } + async fn file( &mut self, source: &S, size: u64, hash: Option, writer: &mut TrackingIO, - ) -> Result { + ) -> Result { let mut reader = source.reader().await?; let mut hasher = blake3::Hasher::new(); - let mut layout = FileLayout { - block: writer.position(), + let mut layout = PendingLayout { + first: self.submitted, size, sparse: 0, blocks: Vec::new(), @@ -194,10 +306,11 @@ impl DataWriter { hasher.update(&buffer); } if buffer.iter().all(|b| *b == 0) { - layout.blocks.push(0); + layout.blocks.push(None); layout.sparse += self.block_size as u64; } else { - layout.blocks.push(self.block(&buffer, writer).await?); + let block = std::mem::replace(&mut buffer, vec![0; self.block_size]); + layout.blocks.push(Some(self.block(block, writer).await?)); } remaining -= self.block_size as u64; } @@ -210,7 +323,7 @@ impl DataWriter { if self.tail.len() + bytes.len() > self.block_size { self.flush_fragment(writer).await?; } - layout.fragment = u32::try_from(self.fragments.len()) + layout.fragment = u32::try_from(self.fragment_blocks.len()) .map_err(|_| invalid("too many SquashFS fragments"))?; layout.offset = self.tail.len() as u32; self.tail.extend_from_slice(bytes); @@ -315,7 +428,7 @@ impl InodeTables { &mut self, index: usize, node: &FlatNode<'_, S>, - layouts: &[Option>], + layouts: &[Option], nodes: &[FlatNode<'_, S>], ) -> std::io::Result<()> { self.references[index] = self.inodes.reference()?; @@ -512,18 +625,29 @@ async fn indexed_table( impl Squashfs { /// Writes an image at the current position and leaves the output after its 4 KiB padding. /// Identical contents, inode attributes, options, and Zstd version produce identical bytes, - /// independent of insertion order and which hardlink carries the file source. + /// independent of insertion order, which hardlink carries the file source, and how many + /// data blocks compress concurrently. + /// Compresses data blocks on the global rayon pool. /// Rejects symlink targets above 4095 bytes for lossless reads on 4 KiB-page kernels. pub async fn serialize( &self, writer: &mut W, + ) -> Result<(), Error> { + let queue_depth = rayon::current_num_threads() * QUEUED_PER_THREAD; + self.serialize_with_queue_depth(writer, queue_depth).await + } + + async fn serialize_with_queue_depth( + &self, + writer: &mut W, + queue_depth: usize, ) -> Result<(), Error> { let nodes = flatten(self.root())?; let base = writer.stream_position().await?; let mut output = TrackingIO::new(0, &mut *writer); output.write_all(&[0; Superblock::SIZE]).await?; - let mut data = DataWriter::new(self.options); - let mut layouts = vec![None; nodes.len()]; + let mut data = DataWriter::new(self.options, queue_depth, output.position()); + let mut pending = vec![None; nodes.len()]; let mut duplicates = BTreeMap::new(); for (index, node) in nodes.iter().enumerate() { if let NodeContents::File(source) = &node.node.contents { @@ -543,10 +667,14 @@ impl Squashfs { } layout }; - layouts[index] = Some(layout); + pending[index] = Some(layout); } } - data.flush_fragment(&mut output).await?; + let (written, fragments) = data.finish(&mut output).await?; + let layouts: Vec<_> = pending + .iter() + .map(|layout| layout.as_deref().map(|layout| written.layout(layout))) + .collect(); let level = self.options.compression_level(); let mut tables = InodeTables::new(&nodes, level)?; for (index, node) in nodes.iter().enumerate() { @@ -567,11 +695,10 @@ impl Squashfs { header.directory_table = output.position(); output.write_all(&tables.directories.finish()?).await?; let mut fragment_bytes = Vec::new(); - for fragment in &data.fragments { + for fragment in &fragments { fragment.serialize(&mut fragment_bytes)?; } - header.fragment_count = data - .fragments + header.fragment_count = fragments .len() .try_into() .map_err(|_| invalid("too many SquashFS fragments"))?; diff --git a/shared-libs/crates/start-core/src/util/squashfs/write/tests.rs b/shared-libs/crates/start-core/src/util/squashfs/write/tests.rs index ae898eef77..5746ff6fd3 100644 --- a/shared-libs/crates/start-core/src/util/squashfs/write/tests.rs +++ b/shared-libs/crates/start-core/src/util/squashfs/write/tests.rs @@ -581,3 +581,61 @@ async fn rejects_short_growing_and_mutating_sources() { assert!(image.serialize(&mut Cursor::new(Vec::new())).await.is_err()); } } + +fn data_block_fixture() -> Squashfs { + let mut contents = DirectoryContents::new(); + let text: Vec = (0u64..200_000) + .flat_map(|line| format!("line {line} value {}\n", line * line % 977).into_bytes()) + .collect(); + contents.insert("text", file(0o644, &text)).unwrap(); + contents.insert("text-copy", file(0o644, &text)).unwrap(); + contents + .insert("random", file(0o644, &random_bytes(700_001))) + .unwrap(); + let mut holey = random_bytes(131072); + holey.extend(vec![0; 262144]); + holey.extend(&text[..200_000]); + contents.insert("holey", file(0o644, &holey)).unwrap(); + for index in 0u32..400 { + let size = 1 + (index as usize * 7919) % 3000; + contents + .insert_path( + format!("small/{index:03}"), + file(0o644, &text[index as usize..index as usize + size]), + ) + .unwrap(); + } + image(contents) +} + +/// Expected hashes pin the bytes of already-published images. +#[tokio::test] +async fn data_block_bytes_are_independent_of_compression_queue_depth() { + let mut small_blocks = Options::new(4096, 3).unwrap(); + small_blocks.deduplicate = false; + for (options, expected) in [ + ( + Options::default(), + "b5647f9c602c31119c91ca05c67201a262376b3db5d79149e20910611a8b3d19", + ), + ( + small_blocks, + "1f93fe067b61a8e38aaef6e8df1ccbe8cc4d90605ff87e7964b6409e8c8bef52", + ), + ] { + let mut image = data_block_fixture(); + image.options = options; + for queue_depth in [1, 2, 3, 64] { + let mut output = Cursor::new(Vec::new()); + image + .serialize_with_queue_depth(&mut output, queue_depth) + .await + .unwrap(); + assert_eq!( + blake3::hash(output.get_ref()).to_hex().as_str(), + expected, + "queue depth {queue_depth}" + ); + } + } +} From 436f6a0a43f7668698f5b32b69a29a25889e74f0 Mon Sep 17 00:00:00 2001 From: Helix the White <267227783+helix-white@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:08:58 -0700 Subject: [PATCH 12/38] fix(storage): unify volume mapping and simplify shared-volume revocation (#4793) * fix(storage): apply the base idmap to local shared volumes Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * refactor(storage): share service filesystem ownership mapping Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * fix(storage): migrate existing shared volume ownership at boot Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * fix(sdk): retire completed health-check deadlines Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * fix(storage): preserve clone ACL and capability metadata Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * fix(storage): retire shared-volume access by runtime incarnation Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * fix(storage): make shared-volume revocation best effort Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * fix(service): preserve replacement after shutdown errors Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * fix(storage): detach SDK-managed shared-volume binds Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * refactor(storage): simplify shared-volume mount requests Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * docs(storage): align shared-volume notes with single host request Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol --------- Co-authored-by: helix-white <267227783+helix-a@users.noreply.github.com> --- .../start-os/changelog/minor-added-volumes.md | 3 +- .../changelog/patch-fixed-bind-propagation.md | 5 + .../changelog/patch-fixed-reflink-metadata.md | 5 + .../container-runtime/ARCHITECTURE.md | 21 +- .../container-runtime/package-lock.json | 6 +- .../src/Adapters/EffectCreator.test.ts | 2 +- projects/start-os/docs/src/shared-volumes.md | 6 +- projects/start-sdk/ARCHITECTURE.md | 2 + .../changelog/minor-added-shared-volumes.md | 1 + .../changelog/patch-fixed-health-deadlines.md | 5 + projects/start-sdk/docs/src/shared-volumes.md | 8 +- .../lib/health/checkFns/checkPortListening.ts | 18 +- .../lib/health/checkFns/checkWebUrl.ts | 4 +- .../start-sdk/lib/health/checkFns/index.ts | 10 +- .../lib/health/checkFns/runHealthScript.ts | 18 +- .../lib/test/health.readyCheck.test.ts | 29 +- .../lib/test/health.timeouts.test.ts | 51 ++ projects/start-sdk/lib/test/pathQueue.test.ts | 22 + .../start-sdk/lib/test/sharedVolumes.test.ts | 121 +++ projects/start-sdk/lib/util/PathQueue.ts | 16 + projects/start-sdk/lib/util/SubContainer.ts | 35 +- projects/start-sdk/lib/util/fileAccess.ts | 13 +- shared-libs/crates/start-core/ARCHITECTURE.md | 10 +- .../crates/start-core/locales/i18n.yaml | 7 + .../start-core/src/backup/target/catalog.rs | 8 +- .../src/backup/target/catalog/tests.rs | 2 +- .../crates/start-core/src/backup/volume.rs | 39 +- .../crates/start-core/src/context/rpc.rs | 5 + .../src/disk/mount/filesystem/cifs.rs | 36 +- .../src/disk/mount/filesystem/syscall.rs | 76 +- .../src/disk/mount/filesystem/syscall_stub.rs | 9 +- .../crates/start-core/src/lxc/filesystem.rs | 194 +++++ shared-libs/crates/start-core/src/lxc/mod.rs | 13 +- .../src/service/effects/bind_mount.rs | 4 +- .../src/service/effects/dependency.rs | 217 +----- .../src/service/effects/shared_volumes.rs | 66 +- .../src/service/effects/subcontainer/mod.rs | 3 +- .../src/service/persistent_container.rs | 33 +- .../start-core/src/service/service_map.rs | 3 +- .../start-core/src/shared_volumes/access.rs | 92 +++ .../start-core/src/shared_volumes/mod.rs | 135 ++-- .../start-core/src/shared_volumes/mounts.rs | 687 +++++------------- .../src/shared_volumes/mounts/tests.rs | 416 +++++++++++ .../start-core/src/shared_volumes/source.rs | 69 +- .../src/shared_volumes/source/ownership.rs | 210 ++++++ .../src/shared_volumes/source/tests.rs | 50 +- .../start-core/src/util/actor/concurrent.rs | 194 +++-- .../crates/start-core/src/util/actor/mod.rs | 63 +- .../start-core/src/util/actor/simple.rs | 60 +- .../crates/start-core/src/util/btrfs.rs | 20 +- .../crates/start-core/src/util/clone.rs | 71 +- .../crates/start-core/src/util/future.rs | 42 +- .../ts-modules/start-core/lib/Effects.ts | 2 +- 53 files changed, 2133 insertions(+), 1104 deletions(-) create mode 100644 projects/start-os/changelog/patch-fixed-bind-propagation.md create mode 100644 projects/start-os/changelog/patch-fixed-reflink-metadata.md create mode 100644 projects/start-sdk/changelog/patch-fixed-health-deadlines.md create mode 100644 projects/start-sdk/lib/test/health.timeouts.test.ts create mode 100644 projects/start-sdk/lib/test/pathQueue.test.ts create mode 100644 projects/start-sdk/lib/util/PathQueue.ts create mode 100644 shared-libs/crates/start-core/src/lxc/filesystem.rs create mode 100644 shared-libs/crates/start-core/src/shared_volumes/access.rs create mode 100644 shared-libs/crates/start-core/src/shared_volumes/mounts/tests.rs create mode 100644 shared-libs/crates/start-core/src/shared_volumes/source/ownership.rs diff --git a/projects/start-os/changelog/minor-added-volumes.md b/projects/start-os/changelog/minor-added-volumes.md index 8b2af2ec33..9cb9a119e0 100644 --- a/projects/start-os/changelog/minor-added-volumes.md +++ b/projects/start-os/changelog/minor-added-volumes.md @@ -5,6 +5,7 @@ release-notes: true - Share data between services, or with other devices, using local folders, folders on external drives and CIFS shares in System → Shared Volumes, with separate No Access, Read and Read/write grants for each supported service. Format a drive while adding it as a volume, update a CIFS share's connection details, and see each volume's availability, free space and source errors on the same page. Managed local folders and backup targets survive server restarts on the data drive. Deleting a volume permanently removes managed local data but preserves external-drive and network-share contents. - Attached-drive lists update automatically. Shared-volume status, free space and source errors refresh after drive and network changes, with mounted shares following the kernel's connection state and periodic free-space checks. Service and backup mount requests reject disconnected shares without tearing down active mounts. Services refresh shared-volume mounts after drive replacement, older attachment cleanup leaves replacement mounts usable, and healthy idle shares avoid repeated network connections. - Keep unsaved names, folder edits and discard warnings while volume, backup-target or drive updates arrive. Clear vanished drive or partition choices without automatically selecting formatting; removal or changed drive details during erase confirmation require a fresh choice. CIFS connection changes notify reactive services; existing mounts keep their source until remounted or restarted. -- Services can treat missing registered folders as unavailable without accepting invalid mount requests. +- Access changes deny future unauthorized mounts and detach incompatible SDK-managed mounts. Revocation is best-effort: independently created extra mounts and open files can remain usable. +- Services can treat missing registered folders as unavailable without accepting invalid mount requests. Local shared folders preserve service file ownership across mounts and backup restores; existing prerelease folders migrate automatically without copying file data. - Manage volumes and backup targets by name, with source error messages highlighted in red and a loading state while backup history is fetched. Partitions that already contain a StartOS backup are marked when adding a drive; stored CIFS targets and credentials carry forward automatically. - Back up volumes independently of services and restore them as new local copies without overwriting existing data. Backup destinations cannot overlap source folders through case variations or local directory aliases. Local volumes and targets support fast deletion and remain registered for retry if deletion fails. diff --git a/projects/start-os/changelog/patch-fixed-bind-propagation.md b/projects/start-os/changelog/patch-fixed-bind-propagation.md new file mode 100644 index 0000000000..f1271f6bda --- /dev/null +++ b/projects/start-os/changelog/patch-fixed-bind-propagation.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Keep subcontainer bind mounts independent during cleanup and enforce read-only access on nested mounts. diff --git a/projects/start-os/changelog/patch-fixed-reflink-metadata.md b/projects/start-os/changelog/patch-fixed-reflink-metadata.md new file mode 100644 index 0000000000..eeabb678a5 --- /dev/null +++ b/projects/start-os/changelog/patch-fixed-reflink-metadata.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Converting package volume folders to subvolumes keeps file capabilities and no longer adds inherited ACLs to copied files. diff --git a/projects/start-os/container-runtime/ARCHITECTURE.md b/projects/start-os/container-runtime/ARCHITECTURE.md index bc8d907a73..177c63d508 100644 --- a/projects/start-os/container-runtime/ARCHITECTURE.md +++ b/projects/start-os/container-runtime/ARCHITECTURE.md @@ -32,16 +32,17 @@ This runtime lives at `projects/start-os/container-runtime` and is a Node.js pac ## `/media/startos/` directory (mounted by the host into the container) -| Path | Description | -| -------------------- | ----------------------------------------------------- | -| `volumes//` | Package data volumes (id-mapped, persistent) | -| `assets/` | Read-only assets from s9pk `assets.squashfs` | -| `images//` | Container images (squashfs, used for subcontainers) | -| `images/.env` | Environment variables for image | -| `images/.json` | Image metadata | -| `backup/` | Backup mount point (mounted during backup operations) | -| `rpc/service.sock` | RPC socket (container runtime listens here) | -| `rpc/host.sock` | Host RPC socket (effects callbacks back to host) | +| Path | Description | +| -------------------- | ------------------------------------------------------------------ | +| `volumes//` | Package data volumes (id-mapped, persistent) | +| `shared-volumes/` | Host-owned shared sources and read-only placeholder for host binds | +| `assets/` | Read-only assets from s9pk `assets.squashfs` | +| `images//` | Container images (squashfs, used for subcontainers) | +| `images/.env` | Environment variables for image | +| `images/.json` | Image metadata | +| `backup/` | Backup mount point (mounted during backup operations) | +| `rpc/service.sock` | RPC socket (container runtime listens here) | +| `rpc/host.sock` | Host RPC socket (effects callbacks back to host) | ## RPC protocol diff --git a/projects/start-os/container-runtime/package-lock.json b/projects/start-os/container-runtime/package-lock.json index 008f8bd145..e8aa0e7cb1 100644 --- a/projects/start-os/container-runtime/package-lock.json +++ b/projects/start-os/container-runtime/package-lock.json @@ -64,7 +64,7 @@ }, "../../start-sdk/dist": { "name": "@start9labs/start-sdk", - "version": "4.2.0", + "version": "5.0.0", "bundleDependencies": [ "@start9labs/start-core" ], @@ -79,13 +79,13 @@ "@vercel/ncc": "^0.38.4", "deep-equality-data-structures": "^2.0.0", "eslint": "^9.39.4", - "fast-xml-parser": "~5.7.0", + "fast-xml-parser": "^5.12.1", "ini": "^5.0.0", "isomorphic-fetch": "^3.0.0", "mime": "^4.1.0", "prettier": "3.8.3", "typescript": "^6.0.3", - "typescript-eslint": "^8.61.0", + "typescript-eslint": "^8.73.0", "yaml": "^2.8.3", "zod": "4.6.7" }, diff --git a/projects/start-os/container-runtime/src/Adapters/EffectCreator.test.ts b/projects/start-os/container-runtime/src/Adapters/EffectCreator.test.ts index 1d6bc01730..9c15529eb3 100644 --- a/projects/start-os/container-runtime/src/Adapters/EffectCreator.test.ts +++ b/projects/start-os/container-runtime/src/Adapters/EffectCreator.test.ts @@ -501,7 +501,7 @@ describe('generated effects RPC boundary', () => { { kind: 'unavailable', reason: 'sourceUnavailable' }, { kind: 'unavailable', reason: 'timeout' }, ])( - 'preserves shared-volume mount outcome %j and original fields', + 'delegates shared-volume mounting once and preserves outcome %j and original fields', async outcome => { const effects = makeEffects({ eventId: null }) const options = Object.freeze({ diff --git a/projects/start-os/docs/src/shared-volumes.md b/projects/start-os/docs/src/shared-volumes.md index a167501dfb..eded187ec1 100644 --- a/projects/start-os/docs/src/shared-volumes.md +++ b/projects/start-os/docs/src/shared-volumes.md @@ -28,16 +28,16 @@ Use a volume's **Manage** dialog, or the service's **Shared Volumes** page. Each The **Shared Volumes** tab appears only for services that support shared volumes. Creating a volume grants access to no services automatically. Multiple services can use the same volume with different access modes. -Revoking access detaches that service's attachments without detaching other consumers. How a service responds to missing storage depends on its package. Prefer volumes for optional media, documents and other shared files rather than operation-critical databases. +Revocation is best-effort. Access changes control future mount requests and detach incompatible SDK-managed mounts. Extra mounts created independently by a service and open files can remain usable. Services that read their volume configuration reactively refresh affected workloads through their normal lifecycle; other consumers retain their own access. A saved **No Access** or **Read** setting does not prove earlier access has ended. Prefer volumes for optional media, documents and other shared files rather than operation-critical databases. ## Remove a volume Remove a volume from its **Manage** dialog. Removing revokes all service access, and what happens to the data depends on the source: -- For a managed **Local folder**, the button reads **Delete**. It permanently deletes the folder and its contents after attachments are detached, so StartOS asks you to type the volume's name to confirm. +- For a managed **Local folder**, the button reads **Delete**. It permanently deletes the folder and its contents after managed source mounts are cleaned up, so StartOS asks you to type the volume's name to confirm. - For an **External drive** or **CIFS share**, **Remove** deletes the volume configuration but leaves the source's contents untouched. -If detachment or local deletion fails, StartOS reports the error and keeps the local volume registered without service access. Retry **Delete** from its **Manage** dialog. Local deletion completes before the request returns; the filesystem can reclaim its space afterward. +If managed-source cleanup or local deletion fails, StartOS reports the error and keeps the local volume registered without service access. Retry **Delete** from its **Manage** dialog. Local deletion completes before the request returns; the filesystem can reclaim its space afterward. Uninstalling or rolling back a consuming service leaves volume contents untouched. diff --git a/projects/start-sdk/ARCHITECTURE.md b/projects/start-sdk/ARCHITECTURE.md index 25288806a1..356872b43f 100644 --- a/projects/start-sdk/ARCHITECTURE.md +++ b/projects/start-sdk/ARCHITECTURE.md @@ -309,6 +309,8 @@ The unified `SubContainer` interface widens `rootfs` / `guid` / `subpath()` t sdk.Mounts.of().mountVolume({ volumeId: 'main', subpath: null, mountpoint: '/data', readonly: false }).mountAssets({ subpath: 'scripts', mountpoint: '/scripts' }).mountDependency({ dependencyId: 'bitcoind', volumeId: 'main', subpath: null, mountpoint: '/bitcoin-data', readonly: true }) ``` +`SubContainer` delegates shared volumes through one `mount-shared-volume` request, like host-owned dependency mounts. StartOS authorizes the grant, installs a permanent inaccessible read-only placeholder, attaches the mapped source and retains its mount descriptor. Read-only staging is internal to the host; the SDK receives only a mounted/unavailable outcome. Host and ordinary CLI binds reuse the common detached-mount policy. Missing source directories are never created. Per-target work shares `PathQueue` with filesystem access serialization, and in-flight mounts hold their subcontainer until completion. Grant changes detach incompatible SDK binds even in manually managed subcontainers. Independent aliases and open handles can remain usable. + ### Health Checks (`lib/health/`) ``` diff --git a/projects/start-sdk/changelog/minor-added-shared-volumes.md b/projects/start-sdk/changelog/minor-added-shared-volumes.md index edf9a46586..7cbb6632b7 100644 --- a/projects/start-sdk/changelog/minor-added-shared-volumes.md +++ b/projects/start-sdk/changelog/minor-added-shared-volumes.md @@ -4,4 +4,5 @@ release-notes: true - Declare support for shared volumes, read user-granted IDs, names and access modes reactively, and choose optional mount outcomes or essential workload mounts. The capability requires StartOS 0.4.3 and a volume-capable Start CLI 3.0.0 or later. Packaging rejects outputs that lose volume support. - Dynamic daemon sets refresh shared-volume consumers and their dependents when sources change, including private connection changes that leave metadata unchanged. Unrelated containers remain running; nested reactive reads reconcile in place. Optional mounts added later do not restart for earlier source changes. +- Shared sources use host-owned staging and registered native data binds, with read-only empty placeholders beneath data mounts. Grant changes deny future unauthorized mounts and detach incompatible SDK-managed binds, including in manually managed subcontainers. Independently created aliases and open handles can retain access. - Services opting in run backups in an isolated runtime without shared mounts or initialization hooks; read backup configuration from persistent state. diff --git a/projects/start-sdk/changelog/patch-fixed-health-deadlines.md b/projects/start-sdk/changelog/patch-fixed-health-deadlines.md new file mode 100644 index 0000000000..5faba25123 --- /dev/null +++ b/projects/start-sdk/changelog/patch-fixed-health-deadlines.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Release unused timeout timers after port, URL and script health checks finish. diff --git a/projects/start-sdk/docs/src/shared-volumes.md b/projects/start-sdk/docs/src/shared-volumes.md index 24ef14ae68..a95d055ae5 100644 --- a/projects/start-sdk/docs/src/shared-volumes.md +++ b/projects/start-sdk/docs/src/shared-volumes.md @@ -20,7 +20,7 @@ This enables the service's **Shared Volumes** controls in StartOS; it requests n const grants = await sdk.getSharedVolumes(effects).const() ``` -Each grant contains `id`, `name`, `readonly` and `availability`. Store the stable GUID `id` in service configuration and use the editable `name` in user-facing choices. Names are neither identities nor paths. The API returns neither host paths nor network credentials. Attached-drive mounts translate ownership through StartOS's existing service UID/GID mapping without changing on-disk owners. Linux mount metadata can reveal the CIFS account name to a granted service; its password remains private. +Each grant contains `id`, `name`, `readonly` and `availability`. Store the stable GUID `id` in service configuration and use the editable `name` in user-facing choices. Names are neither identities nor paths. The catalog returns neither host paths nor network credentials. Local and attached-drive mounts use the same service UID/GID mapping as package-owned volumes; attaching does not rewrite their on-disk owners. Linux mount metadata can reveal the CIFS account name to a granted service; its password remains private. The reader supports `.once()`, `.const()`, `.watch()` and the other [reactive reader methods](file-models.md). Reactive reads are invalidated only when one of the service's own granted volumes changes in a way its mounts depend on: a grant is added or revoked, its access mode changes, it becomes available or unavailable (a status reset to unknown does not count), or its source changes, including updated CIFS connection details. Renames and changes to other volumes do not invalidate them, so a returned name can be stale until the next read. Updating a CIFS share's connection details does not change an existing mount, which keeps the source it opened until the service mounts the volume again. An offline granted volume remains listed; revocation removes it. Availability is the host's last observation, not a mount preflight or a guarantee of continued connectivity. @@ -58,7 +58,7 @@ export async function indexOptionalVolume(effects: T.Effects, id: string) { } ``` -An unavailable source returns `{ kind: 'unavailable', reason: 'sourceUnavailable' | 'timeout' }`. Authorization, invalid paths and internal errors reject instead. Do not catch every rejection as an optional outage. An unavailable source or successful revocation leaves its tracked mountpoint inaccessible and read-only. +An unavailable source returns `{ kind: 'unavailable', reason: 'sourceUnavailable' | 'timeout' }`. Authorization, invalid paths and internal errors reject instead. Do not catch every rejection as an optional outage. An unavailable source leaves a read-only, inaccessible placeholder beneath the mountpoint; replacing a successful mount cannot expose the writable directory below it. Mount outside package-owned and dependency volumes, on the subcontainer's own filesystem. A directory created inside a persistent package volume survives later starts even when nothing mounts there; writes can then land in that directory instead of the shared source. Use the stable volume ID rather than its editable name when deriving paths. If a persistent mountpoint is necessary, remove stale empty directories at startup before launching the workload. @@ -82,7 +82,9 @@ Unavailability rejects construction with the volume ID, mountpoint and reason. A Grants do not pass through dependency mounts. A service reading another service's package volume sees the underlying directory, not shared-volume attachments nested inside it. Each consuming service needs its own grant and mount. -StartOS checks the manifest capability, current grant, access mode and confined paths when attaching. Read-only access cannot be escalated by requesting read/write. Subpaths must remain within the granted source. Revocation detaches the service's attachments without detaching other consumers; applications must respond through their reactive configuration and normal workload lifecycle. +StartOS checks the manifest capability, current grant, access mode and confined paths before staging a source. The SDK makes one host mount request. StartOS creates the placeholder and data bind using the shared native bind machinery and retains the data mount for detachment. Read-only sources remain read-only in the service's user namespace, including independently created bind aliases. Subpaths must remain within the granted source. + +Revocation is best-effort. Grant changes govern future mount requests and detach incompatible SDK-managed binds and staging sources, including in manually managed subcontainers. Independently created aliases and open handles can remain usable. Persisted grants describe authorization intent, not proof that earlier access has ended. Reactive consumers refresh through the ordinary workload lifecycle described above. Removing a volume detaches its SDK-managed binds and stages across its consumers. ## Backup ownership diff --git a/projects/start-sdk/lib/health/checkFns/checkPortListening.ts b/projects/start-sdk/lib/health/checkFns/checkPortListening.ts index cf003a1e56..ed02a539c7 100644 --- a/projects/start-sdk/lib/health/checkFns/checkPortListening.ts +++ b/projects/start-sdk/lib/health/checkFns/checkPortListening.ts @@ -1,6 +1,7 @@ import { Effects } from '@start9labs/start-core/types' import { HealthCheckResult } from './HealthCheckResult' import * as fs from 'node:fs/promises' +import { timeoutPromise } from './index' /** `TCP_LISTEN` in the state column of `/proc/net/tcp{,6}`. */ const TCP_LISTEN = 0x0a @@ -59,6 +60,9 @@ export async function checkPortListening( timeout?: number }, ): Promise { + const deadline = timeoutPromise(options.timeout ?? 1_000, { + message: options.timeoutMessage || `Timeout trying to check port ${port}`, + }) return Promise.race([ Promise.resolve().then(async () => { const hasAddress = @@ -88,16 +92,6 @@ export async function checkPortListening( message: options.errorMessage, } }), - new Promise(resolve => { - setTimeout( - () => - resolve({ - result: 'failure', - message: - options.timeoutMessage || `Timeout trying to check port ${port}`, - }), - options.timeout ?? 1_000, - ) - }), - ]) + deadline.catch(error => ({ result: 'failure', message: error.message })), + ]).finally(deadline.cancel) } diff --git a/projects/start-sdk/lib/health/checkFns/checkWebUrl.ts b/projects/start-sdk/lib/health/checkFns/checkWebUrl.ts index 8d68112ed0..95e08e5eaf 100644 --- a/projects/start-sdk/lib/health/checkFns/checkWebUrl.ts +++ b/projects/start-sdk/lib/health/checkFns/checkWebUrl.ts @@ -25,7 +25,9 @@ export const checkWebUrl = async ( errorMessage = `Error while fetching URL: ${url}`, } = {}, ): Promise => { - return Promise.race([fetch(url), timeoutPromise(timeout)]) + const deadline = timeoutPromise(timeout) + return Promise.race([fetch(url), deadline]) + .finally(deadline.cancel) .then( x => ({ diff --git a/projects/start-sdk/lib/health/checkFns/index.ts b/projects/start-sdk/lib/health/checkFns/index.ts index c493171d5b..b65d8c6008 100644 --- a/projects/start-sdk/lib/health/checkFns/index.ts +++ b/projects/start-sdk/lib/health/checkFns/index.ts @@ -9,11 +9,15 @@ export { checkWebUrl } from './checkWebUrl' * * @param ms - Timeout duration in milliseconds * @param options.message - Custom error message (defaults to "Timed out") - * @returns A promise that never resolves, only rejects after the timeout + * @returns A rejecting deadline; `cancel()` clears an unused timer. */ export function timeoutPromise(ms: number, { message = 'Timed out' } = {}) { - return new Promise((resolve, reject) => - setTimeout(() => reject(new Error(message)), ms), + let timer!: ReturnType + return Object.assign( + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(message)), ms) + }), + { cancel: () => clearTimeout(timer) }, ) } export { runHealthScript } diff --git a/projects/start-sdk/lib/health/checkFns/runHealthScript.ts b/projects/start-sdk/lib/health/checkFns/runHealthScript.ts index d945e05252..56378419e1 100644 --- a/projects/start-sdk/lib/health/checkFns/runHealthScript.ts +++ b/projects/start-sdk/lib/health/checkFns/runHealthScript.ts @@ -26,15 +26,15 @@ export const runHealthScript = async ( `Have ran script ${runCommand} and the result: ${res}`, } = {}, ): Promise => { - const res = await Promise.race([ - subcontainer.execFail(runCommand), - timeoutPromise(timeout), - ]).catch(e => { - console.warn(errorMessage) - console.warn(JSON.stringify(e)) - console.warn(e.toString()) - throw { result: 'failure', message: errorMessage } as HealthCheckResult - }) + const deadline = timeoutPromise(timeout) + const res = await Promise.race([subcontainer.execFail(runCommand), deadline]) + .finally(deadline.cancel) + .catch(e => { + console.warn(errorMessage) + console.warn(JSON.stringify(e)) + console.warn(e.toString()) + throw { result: 'failure', message: errorMessage } as HealthCheckResult + }) return { result: 'success', message: message(res.stdout.toString()), diff --git a/projects/start-sdk/lib/test/health.readyCheck.test.ts b/projects/start-sdk/lib/test/health.readyCheck.test.ts index 1498f4ba59..7e0e1e270b 100644 --- a/projects/start-sdk/lib/test/health.readyCheck.test.ts +++ b/projects/start-sdk/lib/test/health.readyCheck.test.ts @@ -48,7 +48,13 @@ describe('checkPortListening', () => { const procNet = (tcp: string) => (path: string) => Promise.resolve(path === '/proc/net/tcp' ? tcp : header) - afterEach(() => readFile.mockReset()) + beforeEach(() => jest.useFakeTimers()) + afterEach(() => { + const timers = jest.getTimerCount() + jest.useRealTimers() + readFile.mockReset() + expect(timers).toBe(0) + }) it('is not satisfied by connections left behind after the listener exits', async () => { readFile.mockImplementation(procNet(leftoverConnections)) @@ -56,6 +62,27 @@ describe('checkPortListening', () => { expect(result).toEqual({ result: 'failure', message: 'not listening' }) }) + it('releases the deadline when reading the socket table fails', async () => { + readFile.mockRejectedValue(new Error('unreadable')) + await expect( + checkPortListening({} as never, 50001, options), + ).rejects.toThrow('unreadable') + }) + + it('reports the configured timeout when a socket-table read remains pending', async () => { + readFile.mockReturnValue(new Promise(() => {})) + const result = checkPortListening({} as never, 50001, { + ...options, + timeout: 5, + timeoutMessage: 'slow', + }) + await jest.advanceTimersByTimeAsync(5) + await expect(result).resolves.toEqual({ + result: 'failure', + message: 'slow', + }) + }) + it('is satisfied by a listening socket', async () => { readFile.mockImplementation(procNet(listening)) const result = await checkPortListening({} as never, 50001, options) diff --git a/projects/start-sdk/lib/test/health.timeouts.test.ts b/projects/start-sdk/lib/test/health.timeouts.test.ts new file mode 100644 index 0000000000..6f51b3085a --- /dev/null +++ b/projects/start-sdk/lib/test/health.timeouts.test.ts @@ -0,0 +1,51 @@ +import { + checkWebUrl, + runHealthScript, + timeoutPromise, +} from '../health/checkFns' + +beforeEach(() => { + jest.useFakeTimers() + jest.spyOn(console, 'warn').mockImplementation(() => {}) + jest.spyOn(console, 'error').mockImplementation(() => {}) +}) +afterEach(() => { + const timers = jest.getTimerCount() + jest.useRealTimers() + jest.restoreAllMocks() + expect(timers).toBe(0) +}) + +test('a caller can retire an unused deadline', () => { + const deadline = timeoutPromise(30_000) + expect(jest.getTimerCount()).toBe(1) + deadline.cancel() +}) + +test('web checks retire deadlines on response and rejection', async () => { + const fetch = jest.spyOn(globalThis, 'fetch') + fetch.mockResolvedValueOnce({} as Response) + await expect( + checkWebUrl({} as never, 'https://example.invalid'), + ).resolves.toMatchObject({ result: 'success' }) + expect(jest.getTimerCount()).toBe(0) + fetch.mockRejectedValueOnce(new Error('offline')) + await expect( + checkWebUrl({} as never, 'https://example.invalid'), + ).resolves.toMatchObject({ result: 'failure' }) +}) + +test('script checks retire deadlines on completion and rejection', async () => { + const execFail = jest + .fn() + .mockResolvedValueOnce({ stdout: Buffer.from('ready') }) + const subcontainer = { execFail } as never + await expect(runHealthScript(['probe'], subcontainer)).resolves.toMatchObject( + { result: 'success' }, + ) + expect(jest.getTimerCount()).toBe(0) + execFail.mockRejectedValueOnce(new Error('failed')) + await expect(runHealthScript(['probe'], subcontainer)).rejects.toMatchObject({ + result: 'failure', + }) +}) diff --git a/projects/start-sdk/lib/test/pathQueue.test.ts b/projects/start-sdk/lib/test/pathQueue.test.ts new file mode 100644 index 0000000000..aaa83d44a2 --- /dev/null +++ b/projects/start-sdk/lib/test/pathQueue.test.ts @@ -0,0 +1,22 @@ +import { PathQueue } from '../util/PathQueue' + +test('same-path work remains ordered after rejection while other paths proceed', async () => { + const queue = new PathQueue() + const events: string[] = [] + let release!: () => void + const barrier = new Promise(resolve => (release = resolve)) + const first = queue.run('/one', async () => { + events.push('first') + await barrier + throw new Error('failed') + }) + const failure = expect(first).rejects.toThrow('failed') + const second = queue.run('/one', async () => events.push('second')) + await queue.run('/two', async () => events.push('other')) + expect(events).toEqual(['first', 'other']) + release() + await failure + await second + expect(events).toEqual(['first', 'other', 'second']) + await expect(queue.run('/one', async () => 'ready')).resolves.toBe('ready') +}) diff --git a/projects/start-sdk/lib/test/sharedVolumes.test.ts b/projects/start-sdk/lib/test/sharedVolumes.test.ts index bb492f61b4..7487f74354 100644 --- a/projects/start-sdk/lib/test/sharedVolumes.test.ts +++ b/projects/start-sdk/lib/test/sharedVolumes.test.ts @@ -242,6 +242,127 @@ test.each(['eager', 'lazy'] as const)( }, ) +test('shared data and placeholders are owned by one host request, unlike package volume binds', async () => { + const effects = context() + const sub = await SubContainer.eager( + effects, + { imageId: 'main' }, + Mounts.of().mountVolume({ + volumeId: 'main', + mountpoint: '/data', + subpath: null, + readonly: false, + }), + 'test', + ) + try { + await sub.tryMountSharedVolume(options) + const binds = jest + .mocked(subcontainers.execFile) + .mock.calls.filter( + ([command, args]) => + command === 'start-container' && args?.[0] === 'bind-mount', + ) + expect(binds).toHaveLength(1) + expect(binds[0][1]).toEqual( + expect.arrayContaining([ + '--source', + '/media/startos/volumes/main/', + '--target', + '/rootfs/data', + ]), + ) + expect(effects.mountSharedVolume).toHaveBeenCalledTimes(1) + expect(effects.mountSharedVolume).toHaveBeenCalledWith({ + ...options, + subcontainer: 'guid', + }) + } finally { + await sub.destroy() + } +}) + +test('each shared remount delegates once without SDK binds or unmounts', async () => { + const effects = context() + jest + .mocked(effects.mountSharedVolume) + .mockResolvedValueOnce({ kind: 'mounted' }) + .mockResolvedValueOnce({ kind: 'unavailable', reason: 'sourceUnavailable' }) + .mockResolvedValueOnce({ kind: 'mounted' }) + const sub = await SubContainer.eager( + effects, + { imageId: 'main' }, + null, + 'test', + ) + try { + await sub.tryMountSharedVolume(options) + await sub.tryMountSharedVolume({ + ...options, + mountpoint: '/media//./music', + }) + await sub.tryMountSharedVolume(options) + const calls = jest.mocked(subcontainers.execFile).mock.calls + const binds = calls.filter( + ([command, args]) => + command === 'start-container' && args?.[0] === 'bind-mount', + ) + expect(binds).toEqual([]) + expect(effects.mountSharedVolume).toHaveBeenCalledTimes(3) + expect(calls.filter(([command]) => command === 'umount')).toEqual([]) + } finally { + await sub.destroy() + } +}) + +test('an in-flight shared bind holds the subcontainer until it completes', async () => { + const effects = context() + let release!: (value: T.SharedVolumeMountResult) => void + let started!: () => void + const ready = new Promise(resolve => (started = resolve)) + jest.mocked(effects.mountSharedVolume).mockImplementation(() => { + started() + return new Promise(resolve => (release = resolve)) + }) + const sub = await SubContainer.eager( + effects, + { imageId: 'main' }, + null, + 'test', + ) + const mounting = sub.tryMountSharedVolume(options) + await ready + await sub.destroy() + expect(effects.subcontainer.destroyFs).not.toHaveBeenCalled() + release({ kind: 'mounted' }) + await mounting + expect(effects.subcontainer.destroyFs).toHaveBeenCalledWith({ guid: 'guid' }) +}) + +test('a rejected host request never falls back to an SDK bind', async () => { + const effects = context() + const revoked = new Error('shared-volume grant revoked') + jest.mocked(effects.mountSharedVolume).mockRejectedValue(revoked) + const sub = await SubContainer.eager( + effects, + { imageId: 'main' }, + null, + 'test', + ) + try { + await expect(sub.tryMountSharedVolume(options)).rejects.toBe(revoked) + const binds = jest + .mocked(subcontainers.execFile) + .mock.calls.filter( + ([command, args]) => + command === 'start-container' && args?.[0] === 'bind-mount', + ) + expect(binds).toEqual([]) + } finally { + await sub.destroy() + } +}) + test.each(['sourceUnavailable', 'timeout'] as const)( 'optional %s is an outcome and the affected workload is not launched', async reason => { diff --git a/projects/start-sdk/lib/util/PathQueue.ts b/projects/start-sdk/lib/util/PathQueue.ts new file mode 100644 index 0000000000..4eb17a53aa --- /dev/null +++ b/projects/start-sdk/lib/util/PathQueue.ts @@ -0,0 +1,16 @@ +export class PathQueue { + private readonly tails = new Map>() + + run(path: string, operation: () => Promise): Promise { + const result = (this.tails.get(path) ?? Promise.resolve()).then(operation) + const tail = result.then( + () => {}, + () => {}, + ) + this.tails.set(path, tail) + void tail.then(() => { + if (this.tails.get(path) === tail) this.tails.delete(path) + }) + return result + } +} diff --git a/projects/start-sdk/lib/util/SubContainer.ts b/projects/start-sdk/lib/util/SubContainer.ts index 24de6bd955..86d8883ba4 100644 --- a/projects/start-sdk/lib/util/SubContainer.ts +++ b/projects/start-sdk/lib/util/SubContainer.ts @@ -3,12 +3,14 @@ import * as T from '@start9labs/start-core/types' import * as cp from 'child_process' import { promisify } from 'util' import { Buffer } from 'node:buffer' +import { posix } from 'node:path' import { once } from '@start9labs/start-core/util/once' import { Drop } from '@start9labs/start-core/util/Drop' import { logErrorOnce } from '@start9labs/start-core/util/logErrorOnce' import { Mounts } from '../mainFn/Mounts' import { FileMounts } from './fileMounts' import { jsonEnv } from './jsonEnv' +import { PathQueue } from './PathQueue' export const execFile = promisify(cp.execFile) const False = () => false @@ -441,6 +443,7 @@ export class SubContainerEager< private readonly fileMounts = new FileMounts() private sharedMounts = false private sharedVolumeDependency = false + private readonly sharedVolumeQueue = new PathQueue() private leader: cp.ChildProcess private leaderExited: boolean = false @@ -597,11 +600,7 @@ export class SubContainerEager< options.readonly, ) if (isFile) { - if (!this.sharedMounts) { - // Exec namespaces become slaves of this tree and receive its rebinds. - await execFile('mount', ['--make-rshared', this.rootfs]) - this.sharedMounts = true - } + await this.shareMounts() let staged = false await this.fileMounts.add(from, path, async signal => { if (!staged) { @@ -660,6 +659,13 @@ export class SubContainerEager< return this } + private async shareMounts(): Promise { + if (!this.sharedMounts) { + await execFile('mount', ['--make-rshared', this.rootfs]) + this.sharedMounts = true + } + } + /** @internal Includes unsuccessful optional shared-volume mount attempts. */ get dependsOnSharedVolumes(): boolean { return this.sharedVolumeDependency @@ -678,11 +684,20 @@ export class SubContainerEager< ) } this.sharedVolumeDependency = true - await prepBind(null, this.subpath(options.mountpoint), 'directory') - return this.effects.mountSharedVolume({ - ...options, - subcontainer: this.guid, - }) + const release = this.hold() + const target = posix.join(this.rootfs, options.mountpoint) + try { + return await this.sharedVolumeQueue.run(target, async () => { + await prepBind(null, target, 'directory') + await this.shareMounts() + return this.effects.mountSharedVolume({ + ...options, + subcontainer: this.guid, + }) + }) + } finally { + await release() + } } /** diff --git a/projects/start-sdk/lib/util/fileAccess.ts b/projects/start-sdk/lib/util/fileAccess.ts index 32712c70d1..c8fd4f5af3 100644 --- a/projects/start-sdk/lib/util/fileAccess.ts +++ b/projects/start-sdk/lib/util/fileAccess.ts @@ -4,8 +4,9 @@ import { promisify } from 'node:util' import { randomBytes } from 'node:crypto' import * as fs from 'node:fs/promises' import { basename, dirname, resolve } from 'node:path' +import { PathQueue } from './PathQueue' -const queues = new Map>() +const queue = new PathQueue() const heldLocks = new AsyncLocalStorage< { target: string @@ -65,7 +66,7 @@ export async function withFileQueue( if (outer.some(lock => lock.held && lock.target === target)) { return operation(target, signal) } - const result = (queues.get(target) ?? Promise.resolve()).then(async () => { + const result = queue.run(target, async () => { signal.throwIfAborted() const holder = { target, held: true, flocked: false, signal } try { @@ -76,14 +77,6 @@ export async function withFileQueue( holder.held = false } }) - const tail = result.then( - () => {}, - () => {}, - ) - queues.set(target, tail) - void tail.then(() => { - if (queues.get(target) === tail) queues.delete(target) - }) return waitForFileOperation(result, signal) } diff --git a/shared-libs/crates/start-core/ARCHITECTURE.md b/shared-libs/crates/start-core/ARCHITECTURE.md index c137e06521..5e9a64bbb8 100644 --- a/shared-libs/crates/start-core/ARCHITECTURE.md +++ b/shared-libs/crates/start-core/ARCHITECTURE.md @@ -35,7 +35,7 @@ how `startbox` dispatches to `startd`, `start-cli`, etc. The per-entrypoint logi - `src/net/` — Networking (DNS, ACME, WiFi, Tor, WireGuard, gateway/NAT) - `src/net/static_server.rs` — UI and authenticated archive/icon resources. Resource signatures reuse `SignatureAuthorizationContext::check_pubkey` for enrollment. The registry-icon proxy signs exact content-addressed icon URLs under saved registries with the server identity key, using the shared icon path validator and canonical registry enumeration. Signed upstream GETs refuse redirects; other images and archive download hosts retain their existing transport policy. Upstream status, content type and cache policy pass through; unrelated response headers do not. - `src/s9pk/` — S9PK package format (merkle archive) -- `src/lxc/` — LXC container management for packages +- `src/lxc/` — LXC container management for packages. `filesystem::service_filesystem` owns base UID/GID mapping and package-remap composition for package volumes, shared local/disk volumes, runtime rootfs, assets, images and backup views. CIFS supplies service ownership through mount options; host-only staging and backup targets retain raw filesystem views. - `src/install/`, `src/update/` — Package install and OS/package update flows - `src/trusted_keys.rs` — Individual signing-key trust (`TrustedKey.publicKey`), immutable import provenance, committed initial certificates in `src/trusted_keys/initial/`, and legacy OS-signer adapters. `src/trusted_keys/legacy.rs` owns historical grouped-keyring decoding and migration to canonical per-key records; downgrade restores the historical array shape. `src/trusted_keys/connection.rs` atomically records registry connections and advertised-key snapshots. Connecting trusts keys new to the server for packages. Registry index synchronization imports newly listed keys disabled, preserves existing trust and provenance, and issues a `RegistryKeyAdded` notification for each key new to the server and a `RegistryKeyDropped` notification for each key the registry stops offering. Selecting the StartOS update registry trusts its listed keys for OS updates, and that registry cannot be removed. Connected registry listings determine deletion protection, and the last OS-update key cannot lose its trust. `src/sign/gpg.rs` retains original exports and attributes self-certified identities and OpenPGP fingerprints to each signing key. - `src/update/signer_files.rs` — Mirrors OS-update trust to PEM files in the config overlay at `/etc/startos/os-signers`, reconciled from the database during RPC initialization after database migrations. Trust-changing RPCs serialize database mutations and await filesystem persistence. Diagnostic updates read that selection without the data drive, falling back to the image's three production keys only before a selection has been saved. Regular `LocalAuth` verifies its protected cookie, strips caller-supplied `__Auth_local` claims, and injects its authentication result when `get_local_auth` metadata requests it. The diagnostic update endpoint uses that injected result to authorize trust overrides. @@ -133,11 +133,17 @@ Patch-DB provides diff-based state synchronization. Changes to `db/model/public. See [patchdb.md](patchdb.md) for `TypedDbWatch` construction, API, and usage patterns. +## Shared service volumes + +`shared_volumes::mounts` stages confined sources beneath the host-owned `/media/startos/shared-volumes` service path, separate from the package-volume ID namespace. One `mount-shared-volume` request owns authorization, placeholder installation and data attachment. The host pins source and target directories, clones in the service mount namespace, and retains the descriptor returned by attachment. Staging paths and lifecycle remain internal; there is no SDK preparation token or second attachment request. `DetachedMount::configure_bind` owns bind policy for this operation and ordinary `start-container bind-mount`: writable trees retain incoming source propagation; read-only trees are private and recursively read-only. Propagation is set before attachment, preserving cleanup of copies in execution namespaces. Each target keeps an inaccessible read-only placeholder below optional data mounts. Read-only staging crosses into the service user namespace before target binding; the service cannot clear the inherited read-only lock. Retiring a stage leaves independently cloned bindings and open handles usable. + +`shared_volumes::access` weakly registers each live staging table, including tables awaiting asynchronous service cleanup. A mount request re-authorizes after source preparation and holds the management gate through placeholder installation, attachment and registration. Grant changes and removal hold it exclusively while persisting authorization and detaching incompatible SDK-managed targets and stages. This covers manually managed subcontainers without a reactive subscription. The request owns its operation across caller cancellation. Independent aliases and open handles remain outside this best-effort boundary. Persisted grants govern future preparation rather than proving all earlier access has ended. SDK reactive consumers reconcile through their ordinary workload lifecycle. Removing a volume retires its managed stages across services before deleting local data; cleanup failures leave local registration available for retry. + ## Backup targets `Public.backupTargets` owns registered local-folder, external-folder and CIFS destinations. Runtime backup/restore/conversion methods resolve these IDs; setup retains its inline recovery-source contract. Attached drives register through source creation or explicit `backup.target.find`. Find reuses disk discovery and shared source preparation to register partition roots with recognized `StartOSBackupsV2` metadata, without recursive folder discovery or modifying backup contents. Background inventory scans never register targets. The catalog atomically skips already registered filesystem-UUID/root pairs, retaining names and settings; a removed target can be rediscovered with a fresh identity. Boot consumes the historical private CIFS catalog into targets and password-only private credentials, preserving existing CIFS IDs. New IDs are GUIDs independent of connection details. Managed local shared volumes and targets are Btrfs subvolumes beneath the persistent `PACKAGE_DATA` partition at `shared-volumes/` and `backup-targets/`. `DATA_DIR` itself is a volatile mount scaffold. Their path owners also supply generated `managedStorage` directories for clients; the UI presents names rather than opaque catalog IDs or internal managed paths. Migration consumes the legacy private CIFS catalog; rollback to an older same-version development build without registered-target support is unsupported. -`backup::target::catalog` reuses shared source preparation and inspection DTOs. `PreparedFilesystem` shares managed-subvolume validation and filesystem delegation; concrete filesystem types preserve idmapped/shared-CIFS service policy and raw backup policy. `PinnedDirectory` owns confined descriptor opening and its stable path. Prepared callers retain their backing mount; observer reads retain the directory descriptor without mount-cache ownership. Managed local removal reserves the existing mount-cache slot, rejects active users and excludes new mounts through committed subvolume deletion, including nested subvolume roots. Shared-volume removal first revokes grants and detaches consumers. Registration survives failed or interrupted deletion for retry; successful deletion unregisters the source. The Btrfs cleaner reclaims the removed subvolume's space asynchronously. Boot converts ordinary local roots with the package-volume reflink/swap recovery owner before observers or services start. Obsolete pending local deletions recover as named, ungranted registrations during database normalization. External removal preserves contents. Observations reject stale source/credential snapshots and never recreate removed records. Backup, conversion and legacy-cleanup completion refresh target recovery metadata. Legacy CIFS add/update validate the share and existing unencrypted backup metadata before publishing a change; the target lifecycle RPCs retain unavailable configuration intent. Both reuse the target-content inspection owner, where capacity failures are diagnostic rather than a mount or metadata-validation failure. Mounted targets use the same metadata reader for initialization and recovery without opening another mount. The catalog requires validated contents before an unknown or unavailable target becomes available; folder-only status updates cannot clear metadata errors. The backup terminal-report owner persists completed background runs in private history with the target name captured at acceptance; `backup.history.list` pages them newest first. Synchronous request/setup rejection does not create a completed background run. +`backup::target::catalog` reuses shared source preparation and inspection DTOs. `PreparedFilesystem` shares managed-subvolume validation and filesystem delegation; concrete filesystem types preserve idmapped/shared-CIFS service policy and raw backup policy. `PinnedDirectory` owns confined descriptor opening and its stable path. Prepared callers retain their backing mount; observer reads retain the directory descriptor without mount-cache ownership. Managed local removal reserves the existing mount-cache slot, rejects active users and excludes new mounts through committed subvolume deletion, including nested subvolume roots. Shared-volume removal revokes future authorization and retires managed staging sources before deleting local data. Registration survives failed or interrupted deletion for retry; successful deletion unregisters the source. The Btrfs cleaner reclaims the removed subvolume's space asynchronously. Boot converts ordinary local roots with the package-volume reflink/swap recovery owner before observers or services start. Local shared roots carrying the legacy LXC ownership offset are replaced through the inverse ownership view and the same recoverable reflink/swap owner, independently of version-keyed migrations; backup targets retain raw owners. Obsolete pending local deletions recover as named, ungranted registrations during database normalization. External removal preserves contents. Observations reject stale source/credential snapshots and never recreate removed records. Backup, conversion and legacy-cleanup completion refresh target recovery metadata. Legacy CIFS add/update validate the share and existing unencrypted backup metadata before publishing a change; the target lifecycle RPCs retain unavailable configuration intent. Both reuse the target-content inspection owner, where capacity failures are diagnostic rather than a mount or metadata-validation failure. Mounted targets use the same metadata reader for initialization and recovery without opening another mount. The catalog requires validated contents before an unknown or unavailable target becomes available; folder-only status updates cannot clear metadata errors. The backup terminal-report owner persists completed background runs in private history with the target name captured at acceptance; `backup.history.list` pages them newest first. Synchronous request/setup rejection does not create a completed background run. Backup-FS mount caching and trash sweeps use actual directory identity, including through pinned descriptors and aliases; a replacement at the same pathname does not reuse an old encrypted mount. Public source errors redact private cache identities. diff --git a/shared-libs/crates/start-core/locales/i18n.yaml b/shared-libs/crates/start-core/locales/i18n.yaml index 08fa3ad088..7d83c794ed 100644 --- a/shared-libs/crates/start-core/locales/i18n.yaml +++ b/shared-libs/crates/start-core/locales/i18n.yaml @@ -4272,6 +4272,13 @@ tunnel.api.invalid-name: fr_FR: 'Les noms ne doivent pas être vides ni composés uniquement d’espaces, ne doivent contenir aucun caractère de contrôle et doivent comporter au maximum %{max} caractères' pl_PL: 'Nazwy nie mogą być puste ani składać się wyłącznie z białych znaków, nie mogą zawierać znaków sterujących i mogą mieć najwyżej %{max} znaków' +util.actor.runtime-exited: + en_US: The task processor has stopped. + de_DE: Die Aufgabenverarbeitung wurde gestoppt. + es_ES: El procesador de tareas se ha detenido. + fr_FR: Le processeur de tâches est arrêté. + pl_PL: Przetwarzanie zadań zostało zatrzymane. + util.crypto.invalid-backup-key: en_US: "The wrapped backup key is invalid or could not be authenticated." de_DE: "Der verschlüsselte Sicherungsschlüssel ist ungültig oder konnte nicht authentifiziert werden." diff --git a/shared-libs/crates/start-core/src/backup/target/catalog.rs b/shared-libs/crates/start-core/src/backup/target/catalog.rs index 387dd96a2e..788fd04cca 100644 --- a/shared-libs/crates/start-core/src/backup/target/catalog.rs +++ b/shared-libs/crates/start-core/src/backup/target/catalog.rs @@ -15,7 +15,7 @@ use crate::disk::mount::guard::{GenericMountGuard, TmpMountGuard, WeakMountGuard use crate::disk::util::{StartOsRecoveryInfo, has_legacy_backup, recovery_info}; use crate::prelude::*; use crate::shared_volumes::mounts::PreparedSource; -use crate::shared_volumes::source::{self, PreparedFilesystem, SourceDefinition}; +use crate::shared_volumes::source::{self, LocalSubvolume, PreparedFilesystem, SourceDefinition}; use crate::shared_volumes::{ CreateSharedVolumeParams, CreateSharedVolumeSource, SharedVolumeDrive, SharedVolumeInspection, SharedVolumeSource, @@ -64,9 +64,11 @@ pub(crate) struct BackupTargetSource { pub(crate) fn filesystem( id: &BackupTargetId, definition: &SourceDefinition, -) -> PreparedFilesystem, Cifs> { +) -> PreparedFilesystem, Cifs> { match definition.source() { - SharedVolumeSource::Local => PreparedFilesystem::Local(local_path(crate::PACKAGE_DATA, id)), + SharedVolumeSource::Local => { + PreparedFilesystem::Local(LocalSubvolume(local_path(crate::PACKAGE_DATA, id))) + } SharedVolumeSource::Disk { logicalname, .. } => { PreparedFilesystem::Disk(BlockDev::new(logicalname.clone())) } diff --git a/shared-libs/crates/start-core/src/backup/target/catalog/tests.rs b/shared-libs/crates/start-core/src/backup/target/catalog/tests.rs index ea5d927652..8bb3e0d70e 100644 --- a/shared-libs/crates/start-core/src/backup/target/catalog/tests.rs +++ b/shared-libs/crates/start-core/src/backup/target/catalog/tests.rs @@ -6,7 +6,7 @@ use super::*; fn local_filesystem_uses_persisted_package_data_partition() { let id = BackupTargetId::new(); let definition = SourceDefinition::new(SharedVolumeSource::Local, None); - let PreparedFilesystem::Local(path) = filesystem(&id, &definition) else { + let PreparedFilesystem::Local(LocalSubvolume(path)) = filesystem(&id, &definition) else { panic!("local filesystem") }; assert!(path.starts_with(crate::PACKAGE_DATA)); diff --git a/shared-libs/crates/start-core/src/backup/volume.rs b/shared-libs/crates/start-core/src/backup/volume.rs index 3644b1b378..cf2322a6cc 100644 --- a/shared-libs/crates/start-core/src/backup/volume.rs +++ b/shared-libs/crates/start-core/src/backup/volume.rs @@ -13,9 +13,10 @@ use super::target::{BackupTargetId, BackupTargetSource, SharedVolumeBackupInfo, use super::{PackageBackupReport, VolumeBackupReport}; use crate::context::{CliContext, RpcContext}; use crate::disk::mount::backup::BackupMountGuard; +use crate::disk::mount::filesystem::bind::Bind; use crate::disk::mount::filesystem::block_dev::BlockDev; use crate::disk::mount::filesystem::{FileSystem, ReadOnly, ReadWrite}; -use crate::disk::mount::guard::GenericMountGuard; +use crate::disk::mount::guard::{GenericMountGuard, TmpMountGuard}; use crate::disk::mount::util::sync_directory; use crate::prelude::*; use crate::rpc_continuations::Guid; @@ -105,6 +106,7 @@ pub(super) async fn measure_backup( ) } +/// Copies the service view of the volume, retaining host-visible owners. pub(super) async fn backup_volume( ctx: &RpcContext, backup: &BackupMountGuard, @@ -328,7 +330,16 @@ async fn restore_local_copy>>( let mut incomplete = IncompleteRestore(Some(path.clone())); let result = async { source::set_local_permissions(&path).await?; - copy_folder(source, &path).await?; + // Volume backups retain host-visible owners, including the LXC offset. + let unshifted = TmpMountGuard::mount( + &crate::lxc::unshifted_filesystem(Bind::new(source)), + ReadOnly, + ) + .await + .with_kind(ErrorKind::Backup)?; + let copied = copy_folder(unshifted.path(), &path).await; + unshifted.unmount().await?; + copied?; source::set_local_permissions(&path).await?; sync_directory(&path).await?; // Publication can commit after its caller cancels. @@ -595,7 +606,7 @@ mod tests { } #[tokio::test] - #[ignore = "requires BTRFS_TEST_VOLUMES_DIR and UID/GID 100000 mapped"] + #[ignore = "requires root, BTRFS_TEST_VOLUMES_DIR and a private Linux mount namespace"] async fn restore_creates_a_new_local_volume_without_touching_existing_data() { let fixture = crate::util::btrfs::tests::directory(); let old_id = SharedVolumeId::new(); @@ -605,6 +616,8 @@ mod tests { std::fs::create_dir(&source).unwrap(); std::fs::write(old_path.join("sentinel"), b"existing data").unwrap(); std::fs::write(source.join("sentinel"), b"restored data").unwrap(); + std::os::unix::fs::chown(&source, Some(100000), Some(100000)).unwrap(); + std::os::unix::fs::chown(source.join("sentinel"), Some(101000), Some(102000)).unwrap(); let created = restore_local_copy(fixture.path(), &source, "Photos".into(), |id, volume| { assert_ne!(id, old_id); assert_eq!(volume.name, "Photos"); @@ -629,18 +642,32 @@ mod tests { ); assert!(crate::util::btrfs::is_subvolume(local_path(fixture.path(), &created)).await); let metadata = std::fs::metadata(local_path(fixture.path(), &created)).unwrap(); - assert_eq!(metadata.uid(), 100000); - assert_eq!(metadata.gid(), 100000); + assert_eq!(metadata.uid(), 0); + assert_eq!(metadata.gid(), 0); assert_eq!(metadata.permissions().mode() & 0o777, 0o777); + let restored = local_path(fixture.path(), &created).join("sentinel"); + let metadata = std::fs::metadata(&restored).unwrap(); + assert_eq!((metadata.uid(), metadata.gid()), (1000, 2000)); + let view = TmpMountGuard::mount( + &source::SourceFilesystem::local(local_path(fixture.path(), &created)), + ReadOnly, + ) + .await + .unwrap(); + let metadata = std::fs::metadata(view.path().join("sentinel")).unwrap(); + assert_eq!((metadata.uid(), metadata.gid()), (101000, 102000)); + view.unmount().await.unwrap(); } #[tokio::test] - #[ignore = "requires BTRFS_TEST_VOLUMES_DIR and UID/GID 100000 mapped"] + #[ignore = "requires root, BTRFS_TEST_VOLUMES_DIR and a private Linux mount namespace"] async fn failed_restore_copy_or_publication_leaves_no_new_data() { let fixture = crate::util::btrfs::tests::directory(); let source = fixture.path().join("backup"); std::fs::create_dir(&source).unwrap(); std::fs::write(source.join("sentinel"), b"backup data").unwrap(); + std::os::unix::fs::chown(&source, Some(100000), Some(100000)).unwrap(); + std::os::unix::fs::chown(source.join("sentinel"), Some(100000), Some(100000)).unwrap(); let failed_copy = restore_local_copy( fixture.path(), &fixture.path().join("missing"), diff --git a/shared-libs/crates/start-core/src/context/rpc.rs b/shared-libs/crates/start-core/src/context/rpc.rs index c56f7f727b..47c6932cdb 100644 --- a/shared-libs/crates/start-core/src/context/rpc.rs +++ b/shared-libs/crates/start-core/src/context/rpc.rs @@ -76,6 +76,7 @@ pub struct RpcContextSeed { pub net_controller: Arc, pub s9pk_arch: Option<&'static str>, pub services: ServiceMap, + pub(crate) shared_volume_access: crate::shared_volumes::access::SharedVolumeAccess, pub cancellable_installs: SyncMutex>>, pub installing_s9pks: SyncMutex>>, pub metrics_cache: Watch>, @@ -516,6 +517,7 @@ impl RpcContext { Some(crate::ARCH) }, services, + shared_volume_access: Default::default(), cancellable_installs: SyncMutex::new(BTreeMap::new()), installing_s9pks: SyncMutex::new(BTreeMap::new()), metrics_cache, @@ -685,6 +687,9 @@ impl RpcContext { &mut optimize_storage, ) .await?; + for path in crate::shared_volumes::local_volume_paths(&peek)? { + crate::shared_volumes::source::migrate_local_ownership(&path).await?; + } optimize_storage.complete(); init_services.start(); diff --git a/shared-libs/crates/start-core/src/disk/mount/filesystem/cifs.rs b/shared-libs/crates/start-core/src/disk/mount/filesystem/cifs.rs index 5567ee5c65..dd68bc7073 100644 --- a/shared-libs/crates/start-core/src/disk/mount/filesystem/cifs.rs +++ b/shared-libs/crates/start-core/src/disk/mount/filesystem/cifs.rs @@ -231,7 +231,7 @@ mod tests { use crate::disk::mount::guard::MountGuard; use crate::rpc_continuations::Guid; use crate::shared_volumes::SharedVolumeId; - use crate::shared_volumes::mounts::{PreparedSource, PreparedTarget, SharedVolumeMounts}; + use crate::shared_volumes::mounts::{PreparedSource, SharedVolumeMounts}; assert_eq!(std::env::var("VOLUME_CIFS_FIXTURE").as_deref(), Ok("1")); fn definition(hostname: &str, path: &str) -> SharedCifs { SharedCifs(Cifs { @@ -288,29 +288,35 @@ mod tests { let tree = MountGuard::mount(&Bind::new(fixture.path()), fixture.path(), ReadWrite) .await .unwrap(); - let mut mounts = SharedVolumeMounts::default(); + let mut mounts = SharedVolumeMounts::new(fixture.path()).await.unwrap(); let guid = Guid::new(); - let target = PreparedTarget::open( - fixture.path().to_owned(), - "data".into(), + let namespace = std::sync::Arc::new( crate::disk::mount::filesystem::syscall::MountNamespace::for_process( std::process::id(), ) .unwrap(), - ), - ) - .await - .unwrap(); - let location = mounts.prepare(&guid, target).await.unwrap(); + ); mounts - .attach( + .prepare_target( &guid, - location, - SharedVolumeId::new(), + Path::new("data"), + fixture.path(), + Path::new(""), + namespace, + ) + .await + .unwrap(); + mounts + .mount_source( + &guid, + Path::new("data"), + &SharedVolumeId::new(), PreparedSource::open(source.clone(), None).await.unwrap(), true, + fixture.path(), ) + .await .unwrap(); assert!( tokio::fs::write(fixture.path().join("data/forbidden"), b"no") @@ -392,7 +398,8 @@ mod tests { .unwrap(), "cancelled helper left a late mount" ); - mounts.clear(); + mounts.clear().await.unwrap(); + drop(mounts); source.unmount().await.unwrap(); tree.unmount(false).await.unwrap(); } @@ -691,6 +698,7 @@ impl FileSystem for Cifs { } } +/// CIFS lacks `FS_ALLOW_IDMAP`; service ownership comes from mount options. pub struct SharedCifs(pub Cifs); impl FileSystem for SharedCifs { diff --git a/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall.rs b/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall.rs index 44320fa75a..391e0a3c68 100644 --- a/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall.rs +++ b/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall.rs @@ -72,15 +72,20 @@ fn check(ret: i64, what: &'static str) -> Result<(), Error> { } } -/// `open_tree(AT_FDCWD, path, OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC | [AT_RECURSIVE])` -/// — a detached clone of the mount at `path` (its submounts too when -/// `recursive`). +fn clone_flags(recursive: bool) -> libc::c_uint { + OPEN_TREE_CLOEXEC + | OPEN_TREE_CLONE + | if recursive { + AT_RECURSIVE as libc::c_uint + } else { + 0 + } +} + +/// A detached clone of the requested directory, optionally including submounts. pub fn open_tree_clone(path: &Path, recursive: bool) -> Result { let p = cstr_path(path)?; - let mut flags = OPEN_TREE_CLOEXEC | OPEN_TREE_CLONE; - if recursive { - flags |= AT_RECURSIVE as libc::c_uint; - } + let flags = clone_flags(recursive); let r = unsafe { libc::syscall(libc::SYS_open_tree, AT_FDCWD, p.as_ptr(), flags) }; fd_from_raw(r, "open_tree") } @@ -99,10 +104,7 @@ pub fn open_tree_attr_idmap( userns: BorrowedFd, ) -> Result { let p = cstr_path(path)?; - let mut flags = OPEN_TREE_CLOEXEC | OPEN_TREE_CLONE; - if recursive { - flags |= AT_RECURSIVE as libc::c_uint; - } + let flags = clone_flags(recursive); let attr = MountAttr { attr_set: MOUNT_ATTR_IDMAP, attr_clr: 0, @@ -122,15 +124,15 @@ pub fn open_tree_attr_idmap( fd_from_raw(r, "open_tree_attr IDMAP") } -/// Clones a pinned directory without including its child mounts. -pub fn open_tree_clone_fd(source: BorrowedFd) -> Result { +/// A detached clone rooted at a pinned directory, optionally including submounts. +pub fn open_tree_clone_fd(source: BorrowedFd, recursive: bool) -> Result { let empty = cstr_str("")?; let raw = unsafe { libc::syscall( libc::SYS_open_tree, source.as_raw_fd(), empty.as_ptr(), - OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC | AT_EMPTY_PATH as libc::c_uint, + clone_flags(recursive) | AT_EMPTY_PATH as libc::c_uint, ) }; fd_from_raw(raw, "open_tree fd") @@ -201,6 +203,29 @@ pub fn unmount_fd(mount: BorrowedFd) -> Result<(), Error> { check(raw as i64, "umount fd") } +fn mount_id(fd: BorrowedFd) -> Result { + let empty = cstr_str("")?; + let mut stat = std::mem::MaybeUninit::::zeroed(); + check( + unsafe { + libc::syscall( + libc::SYS_statx, + fd.as_raw_fd(), + empty.as_ptr(), + AT_EMPTY_PATH, + libc::STATX_MNT_ID, + stat.as_mut_ptr(), + ) + }, + "statx mount", + )?; + Ok(unsafe { stat.assume_init() }.stx_mnt_id) +} + +pub(crate) fn same_mount(left: BorrowedFd, right: BorrowedFd) -> Result { + Ok(mount_id(left)? == mount_id(right)?) +} + pub(crate) struct MountNamespace(OwnedFd); impl MountNamespace { @@ -265,7 +290,7 @@ fn mount_setattr(fd: BorrowedFd, attr: &MountAttr) -> Result<(), Error> { libc::SYS_mount_setattr, fd.as_raw_fd(), empty.as_ptr(), - AT_EMPTY_PATH, + AT_EMPTY_PATH | AT_RECURSIVE, attr as *const _ as *const libc::c_void, std::mem::size_of::(), ) @@ -283,7 +308,7 @@ impl DetachedMount { pub fn from_fd(fd: OwnedFd) -> Self { Self { fd } } - /// Toggle `MOUNT_ATTR_RDONLY` on the detached mount. + /// Sets read-only state across the detached tree. pub fn set_readonly(&self, ro: bool) -> Result<(), Error> { mount_setattr( self.fd.as_fd(), @@ -294,12 +319,27 @@ impl DetachedMount { }, ) } - /// Isolates the clone from its source's propagation peer group. + /// Isolates the detached tree from source propagation. pub fn set_private(&self) -> Result<(), Error> { + self.set_propagation(libc::MS_PRIVATE as u64) + } + + /// Source-slave for writable trees; private and recursively read-only otherwise. + /// Bind targets never propagate unmounts back to their sources. + pub fn configure_bind(&self, readonly: bool) -> Result<(), Error> { + if readonly { + self.set_private()?; + self.set_readonly(true) + } else { + self.set_propagation(libc::MS_SLAVE as u64) + } + } + + fn set_propagation(&self, propagation: u64) -> Result<(), Error> { mount_setattr( self.fd.as_fd(), &MountAttr { - propagation: libc::MS_PRIVATE as u64, + propagation, ..Default::default() }, ) diff --git a/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall_stub.rs b/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall_stub.rs index 8c988f196c..3603628b7d 100644 --- a/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall_stub.rs +++ b/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall_stub.rs @@ -17,6 +17,10 @@ fn unsupported() -> Result { )) } +pub(crate) fn same_mount(_left: BorrowedFd, _right: BorrowedFd) -> Result { + unsupported() +} + pub(crate) struct MountNamespace; impl MountNamespace { @@ -44,7 +48,7 @@ pub fn open_beneath(_base: &Path, _relative: &Path) -> Result { unsupported() } -pub fn open_tree_clone_fd(_source: BorrowedFd) -> Result { +pub fn open_tree_clone_fd(_source: BorrowedFd, _recursive: bool) -> Result { unsupported() } @@ -67,6 +71,9 @@ impl DetachedMount { pub fn set_private(&self) -> Result<(), Error> { unsupported() } + pub fn configure_bind(&self, _readonly: bool) -> Result<(), Error> { + unsupported() + } pub fn attach(self, _mountpoint: &Path) -> Result<(), Error> { unsupported() } diff --git a/shared-libs/crates/start-core/src/lxc/filesystem.rs b/shared-libs/crates/start-core/src/lxc/filesystem.rs new file mode 100644 index 0000000000..3c6d6122b3 --- /dev/null +++ b/shared-libs/crates/start-core/src/lxc/filesystem.rs @@ -0,0 +1,194 @@ +use crate::disk::mount::filesystem::FileSystem; +use crate::disk::mount::filesystem::idmapped::{IdMap, IdMapped}; + +pub(crate) const BASE_IDMAP: IdMap = IdMap { + from_id: 0, + to_id: 100000, + range: 65536, +}; + +/// Service views apply the LXC base map, followed by package-supplied remaps. +/// Raw filesystem owners remain unshifted on disk. +pub(crate) fn service_filesystem(filesystem: F, custom: &[IdMap]) -> IdMapped { + IdMapped::new(filesystem, service_idmap(custom)) +} + +/// Removes the LXC offset from a service-owned filesystem view. +pub(crate) fn unshifted_filesystem(filesystem: F) -> IdMapped { + IdMapped::new( + filesystem, + vec![IdMap { + from_id: BASE_IDMAP.to_id, + to_id: BASE_IDMAP.from_id, + range: BASE_IDMAP.range, + }], + ) +} + +// Re-idmapping replaces the source map; layered remaps require one composed map. +// Explicit remaps win collisions; ties preserve the lowest on-disk ID. +fn service_idmap(custom: &[IdMap]) -> Vec { + let base = BASE_IDMAP; + if custom.is_empty() { + return vec![base]; + } + let len = base.range as usize; + + let mut host = vec![0u32; len]; + let mut explicit = vec![false; len]; + for d in 0..base.range { + let mut c = d; + let mut touched = false; + for m in custom { + if c >= m.from_id && c - m.from_id < m.range { + c = m.to_id.saturating_add(c - m.from_id); + touched = true; + } + } + host[d as usize] = base.to_id.saturating_add(c); + explicit[d as usize] = touched; + } + + let mut owner: std::collections::HashMap = std::collections::HashMap::new(); + for d in 0..base.range { + match owner.get(&host[d as usize]) { + None => { + owner.insert(host[d as usize], d); + } + Some(&prev) if explicit[d as usize] && !explicit[prev as usize] => { + owner.insert(host[d as usize], d); + } + Some(_) => {} + } + } + let mut keep = vec![None; len]; + for (h, d) in owner { + keep[d as usize] = Some(h); + } + + let mut out = Vec::new(); + let mut d = 0u32; + while (d as usize) < len { + if let Some(h0) = keep[d as usize] { + let mut n = 1u32; + while ((d + n) as usize) < len && keep[(d + n) as usize] == Some(h0.saturating_add(n)) { + n += 1; + } + out.push(IdMap { + from_id: d, + to_id: h0, + range: n, + }); + d += n; + } else { + d += 1; + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn idmap(from_id: u32, to_id: u32, range: u32) -> IdMap { + IdMap { + from_id, + to_id, + range, + } + } + + #[test] + fn empty_custom_is_just_the_base_map() { + assert_eq!(service_idmap(&[]), vec![BASE_IDMAP]); + } + + #[test] + fn override_is_layered_on_top_of_the_base_map() { + assert_eq!( + service_idmap(&[idmap(0, 1000, 1)]), + vec![ + idmap(0, 101000, 1), + idmap(1, 100001, 999), + idmap(1001, 101001, 64535), + ], + ); + } + + #[test] + fn chaining_idmaps_compose_sequentially() { + let custom = [idmap(0, 1000, 1), idmap(1000, 2000, 1)]; + let flat = service_idmap(&custom); + assert_eq!(apply(&flat, 0), Some(102000)); + assert_eq!(apply(&flat, 5), Some(100005)); + assert_eq!(compose_ref(&custom, 1000), Some(102000)); + assert_eq!(apply(&flat, 1000), None); + } + + fn compose_ref(custom: &[IdMap], on_disk: u32) -> Option { + let base = BASE_IDMAP; + if on_disk >= base.range { + return None; + } + let mut c = on_disk; + for m in custom { + if c >= m.from_id && c - m.from_id < m.range { + c = m.to_id.saturating_add(c - m.from_id); + } + } + Some(base.to_id.saturating_add(c)) + } + + fn apply(map: &[IdMap], on_disk: u32) -> Option { + map.iter().find_map(|m| { + (on_disk >= m.from_id && on_disk - m.from_id < m.range) + .then(|| m.to_id.saturating_add(on_disk - m.from_id)) + }) + } + + fn is_valid_uid_map(map: &[IdMap]) -> bool { + let overlaps = |mut v: Vec<(u32, u32)>| { + v.sort(); + v.windows(2).any(|w| w[0].1 > w[1].0) + }; + let froms: Vec<(u32, u32)> = map + .iter() + .map(|m| (m.from_id, m.from_id + m.range)) + .collect(); + let tos: Vec<(u32, u32)> = map.iter().map(|m| (m.to_id, m.to_id + m.range)).collect(); + !overlaps(froms) && !overlaps(tos) + } + + proptest::proptest! { + #![proptest_config(proptest::test_runner::Config { cases: 48, ..proptest::test_runner::Config::default() })] + + #[test] + fn flatten_is_the_injective_restriction_of_composition( + custom in proptest::collection::vec((0u32..60_000, 0u32..60_000, 1u32..2_000), 0..4usize), + ) { + let custom: Vec = custom.into_iter().map(|(f, t, r)| idmap(f, t, r)).collect(); + let flat = service_idmap(&custom); + + proptest::prop_assert!(is_valid_uid_map(&flat), "invalid uid_map: {flat:?}"); + + let comp: Vec> = + (0..BASE_IDMAP.range).map(|d| compose_ref(&custom, d)).collect(); + let mut hits: std::collections::HashMap = std::collections::HashMap::new(); + for c in comp.iter().flatten() { + *hits.entry(*c).or_default() += 1; + } + + for d in 0..BASE_IDMAP.range { + let f = apply(&flat, d); + let c = comp[d as usize]; + proptest::prop_assert!(f.is_none() || f == c, "d={d}: flat={f:?} compose={c:?}"); + if let Some(h) = c { + if hits[&h] == 1 { + proptest::prop_assert_eq!(f, Some(h), "d={} dropped a unique target", d); + } + } + } + } + } +} diff --git a/shared-libs/crates/start-core/src/lxc/mod.rs b/shared-libs/crates/start-core/src/lxc/mod.rs index 8971fc3872..8503ba0603 100644 --- a/shared-libs/crates/start-core/src/lxc/mod.rs +++ b/shared-libs/crates/start-core/src/lxc/mod.rs @@ -20,7 +20,6 @@ use tokio::time::Instant; use crate::context::RpcContext; use crate::disk::mount::filesystem::bind::Bind; use crate::disk::mount::filesystem::block_dev::BlockDev; -use crate::disk::mount::filesystem::idmapped::{IdMap, IdMapped}; use crate::disk::mount::filesystem::overlayfs::OverlayGuard; use crate::disk::mount::filesystem::{MountType, ReadOnly, ReadWrite}; use crate::disk::mount::guard::{GenericMountGuard, MountGuard, TmpMountGuard}; @@ -33,11 +32,9 @@ use crate::util::rpc_client::UnixRpcClient; use crate::util::{FromStrParser, Invoke, new_guid}; use crate::{InvalidId, PackageId}; -pub(crate) const BASE_IDMAP: IdMap = IdMap { - from_id: 0, - to_id: 100000, - range: 65536, -}; +mod filesystem; + +pub(crate) use filesystem::{BASE_IDMAP, service_filesystem, unshifted_filesystem}; fn config_text(guid: &str, lang: &str) -> String { format!( @@ -261,9 +258,9 @@ impl LxcContainer { let rootfs_dir = container_dir.join("rootfs"); let rootfs = OverlayGuard::mount( TmpMountGuard::mount( - &IdMapped::new( + &service_filesystem( BlockDev::new("/usr/lib/startos/container-runtime/rootfs.squashfs"), - vec![BASE_IDMAP], + &[], ), ReadOnly, ) diff --git a/shared-libs/crates/start-core/src/service/effects/bind_mount.rs b/shared-libs/crates/start-core/src/service/effects/bind_mount.rs index d83dffcd8d..92b772174c 100644 --- a/shared-libs/crates/start-core/src/service/effects/bind_mount.rs +++ b/shared-libs/crates/start-core/src/service/effects/bind_mount.rs @@ -90,9 +90,7 @@ pub async fn bind_mount(_: ContainerCliContext, params: BindMountParams) -> Resu DetachedMount::from_fd(fd) }; - if readonly { - detached.set_readonly(true)?; - } + detached.configure_bind(readonly)?; if beneath { detached.attach_beneath(&target)?; diff --git a/shared-libs/crates/start-core/src/service/effects/dependency.rs b/shared-libs/crates/start-core/src/service/effects/dependency.rs index 17fdb718a6..e700c235d7 100644 --- a/shared-libs/crates/start-core/src/service/effects/dependency.rs +++ b/shared-libs/crates/start-core/src/service/effects/dependency.rs @@ -14,10 +14,10 @@ use crate::db::model::package::{ }; use crate::dependencies::DepInfo; use crate::disk::mount::filesystem::bind::{Bind, FileType}; -use crate::disk::mount::filesystem::idmapped::{IdMap, IdMapped}; +use crate::disk::mount::filesystem::idmapped::IdMap; use crate::disk::mount::filesystem::{FileSystem, MountType}; use crate::disk::mount::util::{is_mountpoint, unmount}; -use crate::lxc::BASE_IDMAP; +use crate::lxc::service_filesystem; use crate::s9pk::S9pk; use crate::s9pk::manifest::Manifest; use crate::service::effects::callbacks::CallbackHandler; @@ -45,87 +45,6 @@ pub struct MountTarget { rpc_toolkit::reflect_ts!(MountTarget); rpc_toolkit::ts_export!(MountTarget, namespaces = [""]); -/// The idmap to apply, host-side, for a pointer mount. -/// -/// The SDK idmap is layered *on top of* the LXC base map (the SDK docs: "the -/// base LXC mapping is applied automatically"), and a list of idmaps composes -/// in sequence — each entry remaps the output of the entries before it. We -/// can't stack the layers as separate mounts (re-idmapping an already-idmapped -/// mount *replaces* the mapping, it doesn't compose — verified on a 6.15+ -/// kernel), so the whole stack is collapsed into one equivalent idmap here. -/// -/// Computed pointwise: for each on-disk id, start from its base mapping -/// (`k -> base + k`) and fold the idmaps in order (each is identity outside its -/// `from_id` range). The composition can be non-injective — overriding -/// `0 -> 1000` leaves both on-disk 0 and on-disk 1000 wanting target 1000 — and -/// a uid_map can't map two on-disk ids to one target, so colliding ids are -/// dropped to `nobody`, preferring an explicitly-remapped id over a passthrough. -/// See the proptest in the test module for the exact equivalence to composition. -fn pointer_idmap(custom: &[IdMap]) -> Vec { - let base = BASE_IDMAP; - if custom.is_empty() { - return vec![base]; - } - let len = base.range as usize; - - // Per on-disk id: its composed host target, and whether an idmap touched it. - let mut host = vec![0u32; len]; - let mut explicit = vec![false; len]; - for d in 0..base.range { - // base maps on-disk d -> container d (base.from_id is 0) - let mut c = d; - let mut touched = false; - for m in custom { - if c >= m.from_id && c - m.from_id < m.range { - c = m.to_id.saturating_add(c - m.from_id); - touched = true; - } - } - host[d as usize] = base.to_id.saturating_add(c); - explicit[d as usize] = touched; - } - - // A uid_map target must be unique. On a collision, an explicit remap wins - // over a passthrough; otherwise the lowest on-disk id wins. - let mut owner: std::collections::HashMap = std::collections::HashMap::new(); - for d in 0..base.range { - match owner.get(&host[d as usize]) { - None => { - owner.insert(host[d as usize], d); - } - Some(&prev) if explicit[d as usize] && !explicit[prev as usize] => { - owner.insert(host[d as usize], d); - } - Some(_) => {} - } - } - let mut keep = vec![None; len]; - for (h, d) in owner { - keep[d as usize] = Some(h); - } - - // Coalesce contiguous survivors into extents. - let mut out = Vec::new(); - let mut d = 0u32; - while (d as usize) < len { - if let Some(h0) = keep[d as usize] { - let mut n = 1u32; - while ((d + n) as usize) < len && keep[(d + n) as usize] == Some(h0.saturating_add(n)) { - n += 1; - } - out.push(IdMap { - from_id: d, - to_id: h0, - range: n, - }); - d += n; - } else { - d += 1; - } - } - out -} - #[derive(Debug, Clone, Serialize, Deserialize, visit_rs::VisitFields)] #[serde(rename_all = "camelCase")] pub struct MountParams { @@ -204,9 +123,9 @@ pub async fn mount( unmount(&mountpoint, true).await?; } - IdMapped::new( + service_filesystem( Bind::new(source).with_type(filetype).recursive(true), - pointer_idmap(&idmap), + &idmap, ) .mount( mountpoint, @@ -813,129 +732,6 @@ mod test { } } - #[test] - fn empty_custom_is_just_the_base_map() { - assert_eq!(pointer_idmap(&[]), vec![BASE_IDMAP]); - } - - #[test] - fn override_is_layered_on_top_of_the_base_map() { - // mostro: on-disk 0 -> container 1000 (host 101000); every other id keeps - // its base mapping (k -> 100000 + k), except on-disk 1000, whose base - // target collides with the override and so is dropped (-> nobody). - assert_eq!( - pointer_idmap(&[idmap(0, 1000, 1)]), - vec![ - idmap(0, 101000, 1), // override: on-disk 0 -> container 1000 - idmap(1, 100001, 999), // base: on-disk 1..999 -> container 1..999 - idmap(1001, 101001, 64535), // base: on-disk 1001..65535 (1000 dropped) - ], - ); - } - - #[test] - fn chaining_idmaps_compose_sequentially() { - // idmap 1 maps the OUTPUT range of idmap 0 (0->1000, then 1000->2000), - // so they compose: on-disk 0 -> 1000 -> 2000 (host 102000), not 101000. - let custom = [idmap(0, 1000, 1), idmap(1000, 2000, 1)]; - let flat = pointer_idmap(&custom); - assert_eq!( - apply(&flat, 0), - Some(102000), - "0 composes through both layers" - ); - // an untouched id keeps its base mapping - assert_eq!(apply(&flat, 5), Some(100005)); - // on-disk 1000 ALSO composes to 102000 (passthrough idmap 0, then 1000->2000), - // colliding with on-disk 0 — a single uid_map can't hold both, so it drops. - assert_eq!(compose_ref(&custom, 1000), Some(102000)); - assert_eq!(apply(&flat, 1000), None); - } - - // Reference: the intended (possibly non-injective) composition — base, then - // each idmap applied in sequence to the running value (identity out of range). - fn compose_ref(custom: &[IdMap], on_disk: u32) -> Option { - let base = BASE_IDMAP; - if on_disk >= base.range { - return None; - } - let mut c = on_disk; - for m in custom { - if c >= m.from_id && c - m.from_id < m.range { - c = m.to_id.saturating_add(c - m.from_id); - } - } - Some(base.to_id.saturating_add(c)) - } - - // Apply a flat uid_map to an on-disk id (None == nobody / unmapped). - fn apply(map: &[IdMap], on_disk: u32) -> Option { - map.iter().find_map(|m| { - (on_disk >= m.from_id && on_disk - m.from_id < m.range) - .then(|| m.to_id.saturating_add(on_disk - m.from_id)) - }) - } - - // A valid uid_map: non-overlapping source ranges AND non-overlapping target - // ranges (an idmapped mount is a bijection between the two). - fn is_valid_uid_map(map: &[IdMap]) -> bool { - let overlaps = |mut v: Vec<(u32, u32)>| { - v.sort(); - v.windows(2).any(|w| w[0].1 > w[1].0) - }; - let froms: Vec<(u32, u32)> = map - .iter() - .map(|m| (m.from_id, m.from_id + m.range)) - .collect(); - let tos: Vec<(u32, u32)> = map.iter().map(|m| (m.to_id, m.to_id + m.range)).collect(); - !overlaps(froms) && !overlaps(tos) - } - - proptest::proptest! { - #![proptest_config(proptest::test_runner::Config { cases: 48, ..proptest::test_runner::Config::default() })] - - /// `pointer_idmap` is exactly the injective restriction of the layered - /// composition: it is a valid uid_map, never maps an on-disk id to - /// anything other than what composition would, and preserves every - /// target composition reaches uniquely — only genuine collisions (which - /// a single uid_map cannot represent) drop to nobody. - #[test] - fn flatten_is_the_injective_restriction_of_composition( - custom in proptest::collection::vec((0u32..60_000, 0u32..60_000, 1u32..2_000), 0..4usize), - ) { - let custom: Vec = custom.into_iter().map(|(f, t, r)| idmap(f, t, r)).collect(); - let flat = pointer_idmap(&custom); - - proptest::prop_assert!(is_valid_uid_map(&flat), "invalid uid_map: {flat:?}"); - - let comp: Vec> = - (0..BASE_IDMAP.range).map(|d| compose_ref(&custom, d)).collect(); - let mut hits: std::collections::HashMap = std::collections::HashMap::new(); - for c in comp.iter().flatten() { - *hits.entry(*c).or_default() += 1; - } - - for d in 0..BASE_IDMAP.range { - let f = apply(&flat, d); - let c = comp[d as usize]; - // never wrong: flatten agrees with composition or drops to nobody - proptest::prop_assert!(f.is_none() || f == c, "d={d}: flat={f:?} compose={c:?}"); - // lossless where representable: a uniquely-reached target is kept - if let Some(h) = c { - if hits[&h] == 1 { - proptest::prop_assert_eq!(f, Some(h), "d={} dropped a unique target", d); - } - } - } - } - } - - /// End-to-end check of the host-side mechanism the `mount-pointer` RPC - /// effect runs: build the composed idmap and apply it with `IdMapped` - /// (startd, init_user_ns), then read uids back through the mount. Requires - /// root + a 6.15+ kernel, so it is ignored by default. Run with: - /// sudo --ignored --exact \ - /// service::effects::dependency::test::idmap_host_side_remaps_uids --nocapture #[tokio::test] #[ignore = "requires root + mount privileges"] async fn idmap_host_side_remaps_uids() { @@ -968,12 +764,11 @@ mod test { std::os::unix::fs::chown(src.join(name), Some(uid), Some(uid)).unwrap(); } - // exactly what mount() runs for a pointer mount with idmap [{0->1000}] - IdMapped::new( + service_filesystem( Bind::new(&src) .with_type(FileType::Directory) .recursive(true), - pointer_idmap(&[idmap(0, 1000, 1)]), + &[idmap(0, 1000, 1)], ) .mount(&target, MountType::ReadWrite) .await diff --git a/shared-libs/crates/start-core/src/service/effects/shared_volumes.rs b/shared-libs/crates/start-core/src/service/effects/shared_volumes.rs index c7a4608222..5dcf44f587 100644 --- a/shared-libs/crates/start-core/src/service/effects/shared_volumes.rs +++ b/shared-libs/crates/start-core/src/service/effects/shared_volumes.rs @@ -190,7 +190,17 @@ async fn authorize_mount( ) } +/// Owns authorization, placeholder installation and data attachment through cancellation. pub async fn mount_shared_volume( + context: EffectContext, + params: MountSharedVolumeParams, +) -> Result { + tokio::spawn(mount_shared_volume_owned(context, params)) + .await + .with_kind(ErrorKind::Cancelled)? +} + +async fn mount_shared_volume_owned( context: EffectContext, MountSharedVolumeParams { id, @@ -203,7 +213,7 @@ pub async fn mount_shared_volume( use crate::disk::mount::filesystem::syscall::MountNamespace; use crate::disk::mount::filesystem::{ReadOnly, ReadWrite}; use crate::disk::mount::guard::GenericMountGuard; - use crate::shared_volumes::mounts::{PreparedTarget, confined_relative}; + use crate::shared_volumes::mounts::confined_relative; let service = context.deref()?; let container = &service.seed.persistent_container; container.shared_volumes.lock().await.check_allowed()?; @@ -228,33 +238,34 @@ pub async fn mount_shared_volume( Ok(source) => Ok(source.into_subpath(subpath).await), Err(error) => Err(error), }; + let _admission = service + .seed + .ctx + .shared_volume_access + .management + .read() + .await; + let mut mounts = container.shared_volumes.lock().await; + mounts.check_allowed()?; + authorize_mount(&service, &id, readonly).await?; + let subcontainers = container.subcontainers.lock().await; let lxc = container .lxc_container .get() .or_not_found("lxc container")?; + let root = subcontainers + .get(&subcontainer) + .or_not_found("subcontainer")? + .overlay + .path() + .strip_prefix(lxc.rootfs_dir()) + .with_kind(ErrorKind::Incoherent)?; let pid = lxc.pid().await?; + let service_root = std::path::PathBuf::from(format!("/proc/{pid}/root")); let namespace = std::sync::Arc::new(MountNamespace::for_process(pid)?); - let root = { - let subcontainers = container.subcontainers.lock().await; - std::path::PathBuf::from(format!("/proc/{pid}/root")).join( - subcontainers - .get(&subcontainer) - .or_not_found("subcontainer")? - .overlay - .path() - .strip_prefix(lxc.rootfs_dir()) - .with_kind(ErrorKind::Incoherent)?, - ) - }; - let target = PreparedTarget::open(root, mountpoint, namespace).await?; - let mut mounts = container.shared_volumes.lock().await; - mounts.check_allowed()?; - authorize_mount(&service, &id, readonly).await?; - let subcontainers = container.subcontainers.lock().await; - subcontainers - .get(&subcontainer) - .or_not_found("subcontainer")?; - let location = mounts.prepare(&subcontainer, target).await?; + mounts + .prepare_target(&subcontainer, &mountpoint, &service_root, root, namespace) + .await?; let source = match source { Ok(prepared) => prepared?, Err(error) => { @@ -267,7 +278,16 @@ pub async fn mount_shared_volume( }); } }; - mounts.attach(&subcontainer, location, id, source, readonly)?; + mounts + .mount_source( + &subcontainer, + &mountpoint, + &id, + source, + readonly, + &service_root, + ) + .await?; Ok(SharedVolumeMountResult::Mounted) } diff --git a/shared-libs/crates/start-core/src/service/effects/subcontainer/mod.rs b/shared-libs/crates/start-core/src/service/effects/subcontainer/mod.rs index 6285188dd6..f85cd60c4e 100644 --- a/shared-libs/crates/start-core/src/service/effects/subcontainer/mod.rs +++ b/shared-libs/crates/start-core/src/service/effects/subcontainer/mod.rs @@ -73,7 +73,8 @@ pub async fn destroy_subcontainer_fs( .shared_volumes .lock() .await - .remove_subcontainer(&guid); + .remove_subcontainer(&guid) + .await?; overlay.overlay.unmount(true).await?; } else { tracing::warn!( diff --git a/shared-libs/crates/start-core/src/service/persistent_container.rs b/shared-libs/crates/start-core/src/service/persistent_container.rs index 1e46b2f422..a8b1862820 100644 --- a/shared-libs/crates/start-core/src/service/persistent_container.rs +++ b/shared-libs/crates/start-core/src/service/persistent_container.rs @@ -3,8 +3,8 @@ use std::path::Path; use std::sync::{Arc, Weak}; use std::time::Duration; -use futures::Future; use futures::future::ready; +use futures::{Future, FutureExt}; use imbl::{Vector, vector}; use imbl_value::InternedString; use rpc_toolkit::{Empty, Server, ShutdownHandle}; @@ -15,12 +15,11 @@ use tracing::instrument; use crate::context::RpcContext; use crate::disk::mount::filesystem::bind::Bind; -use crate::disk::mount::filesystem::idmapped::IdMapped; use crate::disk::mount::filesystem::loop_dev::LoopDev; use crate::disk::mount::filesystem::overlayfs::OverlayGuard; use crate::disk::mount::filesystem::{MountType, ReadOnly}; use crate::disk::mount::guard::{GenericMountGuard, MountGuard}; -use crate::lxc::{BASE_IDMAP, HOST_RPC_SERVER_SOCKET, LxcConfig, LxcContainer}; +use crate::lxc::{BASE_IDMAP, HOST_RPC_SERVER_SOCKET, LxcConfig, LxcContainer, service_filesystem}; use crate::net::net_controller::NetService; use crate::prelude::*; use crate::rpc_continuations::Guid; @@ -160,6 +159,18 @@ impl PersistentContainer { }, ) .await?; + let shared_volumes = if s9pk.as_manifest().shared_volumes { + crate::shared_volumes::mounts::SharedVolumeMounts::new(lxc_container.rootfs_dir()) + .boxed() + .await? + } else { + Default::default() + }; + let shared_volumes = Arc::new(Mutex::new(shared_volumes)); + if s9pk.as_manifest().shared_volumes { + ctx.shared_volume_access + .register(&s9pk.as_manifest().id, &shared_volumes); + } let rpc_client = lxc_container.connect_rpc(Some(RPC_CONNECT_TIMEOUT)).await?; let js_mount = MountGuard::mount( &LoopDev::from( @@ -191,9 +202,9 @@ impl PersistentContainer { .join("media/startos/volumes") .join(volume); let mount = MountGuard::mount( - &IdMapped::new( + &service_filesystem( Bind::new(data_dir(DATA_DIR, &s9pk.as_manifest().id, volume)), - vec![BASE_IDMAP], + &[], ), mountpoint, MountType::ReadWrite, @@ -211,7 +222,7 @@ impl PersistentContainer { { vec![ MountGuard::mount( - &IdMapped::new(LoopDev::from(&**sqfs), vec![BASE_IDMAP]), + &service_filesystem(LoopDev::from(&**sqfs), &[]), mountpoint, MountType::ReadWrite, ) @@ -235,7 +246,7 @@ impl PersistentContainer { }; assets.push( MountGuard::mount( - &IdMapped::new(LoopDev::from(&**sqfs), vec![BASE_IDMAP]), + &service_filesystem(LoopDev::from(&**sqfs), &[]), mountpoint, MountType::ReadWrite, ) @@ -269,7 +280,7 @@ impl PersistentContainer { image.clone(), Arc::new( MountGuard::mount( - &IdMapped::new(LoopDev::from(&**sqfs), vec![BASE_IDMAP]), + &service_filesystem(LoopDev::from(&**sqfs), &[]), &mountpoint, ReadOnly, ) @@ -308,7 +319,7 @@ impl PersistentContainer { assets, images, subcontainers: Arc::new(Mutex::new(BTreeMap::new())), - shared_volumes: Arc::new(Mutex::new(Default::default())), + shared_volumes, state: Arc::new(watch::channel(ServiceState::new()).0), net_service: None, destroyed: false, @@ -335,7 +346,7 @@ impl PersistentContainer { .join("media/startos/backup"); tokio::fs::create_dir_all(&mountpoint).await?; tokio::fs::create_dir_all(backup_path).await?; - let bind = IdMapped::new(Bind::new(backup_path), vec![BASE_IDMAP]); + let bind = service_filesystem(Bind::new(backup_path), &[]); MountGuard::mount(&bind, &mountpoint, mount_type).await } @@ -465,7 +476,7 @@ impl PersistentContainer { ) .await; } - shared_volumes.lock().await.clear(); + errs.handle(shared_volumes.lock().await.clear().await); if let Some(net_service) = net_service { net_service.remove_all().await.log_err(); } diff --git a/shared-libs/crates/start-core/src/service/service_map.rs b/shared-libs/crates/start-core/src/service/service_map.rs index 38791ca3c6..829dc647b7 100644 --- a/shared-libs/crates/start-core/src/service/service_map.rs +++ b/shared-libs/crates/start-core/src/service/service_map.rs @@ -102,7 +102,6 @@ fn uninit_target(data_ver: &str, prev: &Manifest, next: &Manifest) -> Result>>>>); impl ServiceMap { @@ -143,6 +142,7 @@ impl ServiceMap { Ok(()) } + /// Attempts replacement even if shutdown fails; a successful load can return a shutdown error. #[instrument(skip_all)] pub async fn load( &self, @@ -635,6 +635,7 @@ impl ServiceRefReloadInfo { self.ctx .services .load(&self.ctx, &self.id, LoadDisposition::Undo) + .boxed() .await } diff --git a/shared-libs/crates/start-core/src/shared_volumes/access.rs b/shared-libs/crates/start-core/src/shared_volumes/access.rs new file mode 100644 index 0000000000..1ef25ad2dd --- /dev/null +++ b/shared-libs/crates/start-core/src/shared_volumes/access.rs @@ -0,0 +1,92 @@ +use std::collections::BTreeMap; +use std::sync::{Arc, Weak}; + +use tokio::sync::{Mutex, RwLock}; + +use super::mounts::SharedVolumeMounts; +use super::{SharedVolumeGrant, SharedVolumeId}; +use crate::PackageId; +use crate::prelude::*; +use crate::util::sync::SyncMutex; + +/// Grant changes deny future mount requests and detach incompatible SDK-managed binds and stages. +/// Independent aliases and open handles remain outside this best-effort boundary. +#[derive(Default)] +pub(crate) struct SharedVolumeAccess { + pub(crate) management: RwLock<()>, + stages: SyncMutex>>>>, +} + +impl SharedVolumeAccess { + pub(crate) fn register(&self, package: &PackageId, mounts: &Arc>) { + self.stages.mutate(|stages| { + let stages = stages.entry(package.clone()).or_default(); + stages.retain(|stage| stage.strong_count() > 0); + stages.push(Arc::downgrade(mounts)); + }); + } + + fn live_stages(&self) -> BTreeMap>>> { + self.stages.mutate(|stages| { + let mut live = BTreeMap::new(); + stages.retain(|package, stages| { + let mounts: Vec<_> = stages.iter().filter_map(Weak::upgrade).collect(); + stages.retain(|stage| stage.strong_count() > 0); + if mounts.is_empty() { + false + } else { + live.insert(package.clone(), mounts); + true + } + }); + live + }) + } + + pub(crate) async fn reconcile_grant( + &self, + package: &PackageId, + volume: &SharedVolumeId, + grant: Option<&SharedVolumeGrant>, + ) -> Result<(), Error> { + let mut errors = ErrorCollection::new(); + for mounts in self.live_stages().remove(package).unwrap_or_default() { + errors.handle(mounts.lock().await.reconcile_grant(volume, grant).await); + } + errors.into_result() + } + + pub(crate) async fn remove_volume(&self, volume: &SharedVolumeId) -> Result<(), Error> { + let mut errors = ErrorCollection::new(); + for mounts in self.live_stages().into_values().flatten() { + errors.handle(mounts.lock().await.reconcile_grant(volume, None).await); + } + errors.into_result() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn registry_tracks_staging_lifetimes_without_owning_them() { + let registry = SharedVolumeAccess::default(); + let package = "consumer".parse().unwrap(); + let first = Arc::new(Mutex::new(SharedVolumeMounts::default())); + let second = Arc::new(Mutex::new(SharedVolumeMounts::default())); + registry.register(&package, &first); + registry.register(&package, &second); + assert_eq!(Arc::strong_count(&first), 1); + assert_eq!(registry.live_stages()[&package].len(), 2); + drop(first); + assert_eq!(registry.live_stages()[&package].len(), 1); + registry + .reconcile_grant(&package, &SharedVolumeId::new(), None) + .await + .unwrap(); + assert!(second.lock().await.check_allowed().is_ok()); + drop(second); + assert!(registry.live_stages().is_empty()); + } +} diff --git a/shared-libs/crates/start-core/src/shared_volumes/mod.rs b/shared-libs/crates/start-core/src/shared_volumes/mod.rs index 9813a5530d..f429470049 100644 --- a/shared-libs/crates/start-core/src/shared_volumes/mod.rs +++ b/shared-libs/crates/start-core/src/shared_volumes/mod.rs @@ -1,4 +1,6 @@ -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; +#[cfg(test)] +use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use std::str::FromStr; @@ -7,6 +9,7 @@ use serde::{Deserialize, Serialize}; use crate::PackageId; +pub(crate) mod access; pub mod mounts; pub mod source; #[cfg(target_os = "linux")] @@ -132,6 +135,12 @@ pub struct SharedVolumeGrant { pub readonly: bool, } +impl SharedVolumeGrant { + pub(crate) fn allows(&self, readonly: bool) -> bool { + readonly || !self.readonly + } +} + rpc_toolkit::reflect_ts!(SharedVolumeGrant); #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, VisitVariants)] @@ -167,7 +176,7 @@ impl SharedVolume { } } -pub(crate) fn managed_local_paths( +pub(crate) fn local_volume_paths( database: &crate::db::model::DatabaseModel, ) -> Result, Error> { let mut paths = Vec::new(); @@ -176,6 +185,13 @@ pub(crate) fn managed_local_paths( paths.push(local_path(crate::PACKAGE_DATA, &id)); } } + Ok(paths) +} + +pub(crate) fn managed_local_paths( + database: &crate::db::model::DatabaseModel, +) -> Result, Error> { + let mut paths = local_volume_paths(database)?; for (id, target) in database.as_public().as_backup_targets().as_entries()? { if matches!(target.as_source().de()?, SharedVolumeSource::Local) { paths.push(crate::backup::target::catalog::local_path( @@ -244,7 +260,7 @@ impl SharedVolume { readonly: bool, ) -> Result<(), Error> { let grant = capable.then(|| self.grants.get(package)).flatten(); - if grant.is_some_and(|grant| readonly || !grant.readonly) { + if grant.is_some_and(|grant| grant.allows(readonly)) { Ok(()) } else { Err(access_denied()) @@ -454,6 +470,7 @@ pub struct SetSharedVolumeGrantParams { rpc_toolkit::reflect_ts!(SetSharedVolumeGrantParams); +/// Applies grant intent before best-effort retirement of incompatible staging sources. pub async fn set_grant( ctx: RpcContext, SetSharedVolumeGrantParams { @@ -461,29 +478,49 @@ pub async fn set_grant( package_id, grant, }: SetSharedVolumeGrantParams, +) -> Result<(), Error> { + tokio::spawn(set_grant_owned(ctx, id, package_id, grant)) + .await + .with_kind(ErrorKind::Cancelled)? +} + +fn validate_grant( + db: &crate::db::model::DatabaseModel, + id: &SharedVolumeId, + package_id: &PackageId, + grant: Option<&SharedVolumeGrant>, ) -> Result<(), Error> { use crate::db::model::package::ManifestPreference; - let service = ctx.services.get(&package_id).await; - let mut mounts = if let Some(service) = service.as_ref() { - Some(service.shared_volume_mounts().lock().await) - } else { - None - }; + if grant.is_some() + && !db + .as_public() + .as_package_data() + .as_idx(package_id) + .or_not_found(package_id)? + .as_state_info() + .as_manifest(ManifestPreference::Old) + .as_shared_volumes() + .de()? + { + return Err(access_denied()); + } + db.as_public() + .as_shared_volumes() + .as_idx(id) + .or_not_found(id)?; + Ok(()) +} + +async fn set_grant_owned( + ctx: RpcContext, + id: SharedVolumeId, + package_id: PackageId, + grant: Option, +) -> Result<(), Error> { + let management = ctx.shared_volume_access.management.write().await; ctx.db .mutate(|db| { - if grant.is_some() - && !db - .as_public() - .as_package_data() - .as_idx(&package_id) - .or_not_found(&package_id)? - .as_state_info() - .as_manifest(ManifestPreference::Old) - .as_shared_volumes() - .de()? - { - return Err(access_denied()); - } + validate_grant(db, &id, &package_id, grant.as_ref())?; let volume = db .as_public_mut() .as_shared_volumes_mut() @@ -498,10 +535,12 @@ pub async fn set_grant( }) .await .result?; - if let Some(mounts) = &mut mounts { - mounts.reconcile_grant(&id, grant.as_ref())?; - } - Ok(()) + let result = ctx + .shared_volume_access + .reconcile_grant(&package_id, &id, grant.as_ref()) + .await; + drop(management); + result } #[derive(Deserialize, Serialize, VisitFields)] @@ -512,36 +551,31 @@ pub struct SharedVolumeParams { rpc_toolkit::reflect_ts!(SharedVolumeParams); -/// Revokes local grants before detachment; failed deletion keeps the registration. +/// Revokes future access before staging cleanup; failed local deletion keeps the registration. pub async fn remove( ctx: RpcContext, SharedVolumeParams { id }: SharedVolumeParams, ) -> Result<(), Error> { - let (source, packages) = ctx.db.mutate(|db| prepare_removal(db, &id)).await.result?; - let mut errors = ErrorCollection::new(); - for package_id in &packages { - let service = ctx.services.get(package_id).await; - if let Some(service) = service.as_ref() { - errors.handle( - service - .shared_volume_mounts() - .lock() - .await - .reconcile_grant(&id, None), - ); - } - } - errors.into_result()?; + tokio::spawn(remove_owned(ctx, id)) + .await + .with_kind(ErrorKind::Cancelled)? +} + +async fn remove_owned(ctx: RpcContext, id: SharedVolumeId) -> Result<(), Error> { + let management = ctx.shared_volume_access.management.write().await; + let source = ctx.db.mutate(|db| prepare_removal(db, &id)).await.result?; + ctx.shared_volume_access.remove_volume(&id).await?; if matches!(source, Some(SharedVolumeSource::Local)) { delete_local_volume(&ctx.db, &id, Path::new(crate::PACKAGE_DATA)).await?; } + drop(management); Ok(()) } fn prepare_removal( db: &mut crate::db::model::DatabaseModel, id: &SharedVolumeId, -) -> Result<(Option, BTreeSet), Error> { +) -> Result, Error> { let source = db .as_public() .as_shared_volumes() @@ -558,7 +592,7 @@ fn prepare_removal( } else { remove_definition(db, id)?; } - Ok((source, db.as_public().as_package_data().keys()?)) + Ok(source) } async fn delete_local_volume( @@ -567,10 +601,11 @@ async fn delete_local_volume( package_data: &Path, ) -> Result<(), Error> { use crate::disk::mount::filesystem::ReadOnly; - use crate::disk::mount::filesystem::bind::Bind; use crate::disk::mount::guard::TmpMountGuard; let path = local_path(package_data, id); - let _unused = TmpMountGuard::reserve_unmounted(&Bind::new(&path), ReadOnly).await?; + let _unused = + TmpMountGuard::reserve_unmounted(&source::SourceFilesystem::local(path.clone()), ReadOnly) + .await?; crate::util::btrfs::delete_volume_root(&path).await?; database.mutate(|db| remove_definition(db, id)).await.result } @@ -714,7 +749,7 @@ mod tests { cifs.to_string(): {"password":"secret"} } } })).unwrap()); - let (source, _) = prepare_removal(&mut db, &local).unwrap(); + let source = prepare_removal(&mut db, &local).unwrap(); assert!(matches!(source, Some(SharedVolumeSource::Local))); prepare_removal(&mut db, &cifs).unwrap(); prepare_removal(&mut db, &disk).unwrap(); @@ -757,6 +792,10 @@ mod tests { } } })); + assert_eq!( + local_volume_paths(&database).unwrap(), + vec![local_path(crate::PACKAGE_DATA, &volume)] + ); let paths: BTreeSet<_> = managed_local_paths(&database) .unwrap() .into_iter() @@ -883,7 +922,7 @@ mod tests { tokio::fs::write(path.join("sentinel"), b"managed contents") .await .unwrap(); - let filesystem = source::SourceFilesystem::Local(path.clone()); + let filesystem = source::SourceFilesystem::local(path.clone()); let held = TmpMountGuard::mount(&filesystem, ReadOnly).await.unwrap(); database .mutate(|db| prepare_removal(db, &id)) diff --git a/shared-libs/crates/start-core/src/shared_volumes/mounts.rs b/shared-libs/crates/start-core/src/shared_volumes/mounts.rs index 7355dee555..f84f4bf513 100644 --- a/shared-libs/crates/start-core/src/shared_volumes/mounts.rs +++ b/shared-libs/crates/start-core/src/shared_volumes/mounts.rs @@ -1,22 +1,23 @@ use std::collections::BTreeMap; -use std::os::fd::{AsFd, AsRawFd, OwnedFd}; +use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd}; use std::os::unix::fs::PermissionsExt; use std::path::{Component, Path, PathBuf}; use std::sync::Arc; use crate::disk::mount::filesystem::syscall::{ - DetachedMount, MountNamespace, open_beneath, open_tree_clone_fd, unmount_fd, + DetachedMount, MountNamespace, open_beneath, open_tree_clone_fd, same_mount, unmount_fd, }; use crate::disk::mount::guard::{GenericMountGuard, TmpMountGuard}; use crate::prelude::*; use crate::rpc_continuations::Guid; use crate::shared_volumes::{SharedVolumeGrant, SharedVolumeId}; +use crate::util::io::TmpDir; + +const SERVICE_ROOT: &str = "media/startos/shared-volumes"; struct AttachedMount { mount: OwnedFd, namespace: Arc, - #[cfg(test)] - fail_detach: bool, } impl AttachedMount { @@ -26,27 +27,29 @@ impl AttachedMount { readonly: bool, namespace: Arc, ) -> Result { - let detached = DetachedMount::from_fd(open_tree_clone_fd(source.as_fd())?); - // Clones inherit target propagation without joining the source's peer group. + let detached = DetachedMount::from_fd(open_tree_clone_fd(source.as_fd(), false)?); detached.set_private()?; detached.set_readonly(readonly)?; let mount = namespace.run(|| detached.attach_to_fd(destination.as_fd()))?; - Ok(Self { - mount, - namespace, - #[cfg(test)] - fail_detach: false, - }) + Ok(Self { mount, namespace }) + } + + fn bind_in_namespace( + source: BorrowedFd, + destination: BorrowedFd, + readonly: bool, + recursive: bool, + namespace: Arc, + ) -> Result { + let mount = namespace.run(|| { + let detached = DetachedMount::from_fd(open_tree_clone_fd(source, recursive)?); + detached.configure_bind(readonly)?; + detached.attach_to_fd(destination) + })?; + Ok(Self { mount, namespace }) } fn detach(&self) -> Result<(), Error> { - #[cfg(test)] - if self.fail_detach { - return Err(Error::new( - std::io::Error::from_raw_os_error(libc::EIO), - ErrorKind::Filesystem, - )); - } self.namespace.run(|| unmount_fd(self.mount.as_fd())) } } @@ -134,55 +137,84 @@ impl GenericMountGuard for PreparedSource { } } -pub(crate) struct PreparedTarget { - location: PathBuf, - directory: OwnedFd, - namespace: Arc, +struct StagingRoot { + _unavailable: AttachedMount, + directory: PinnedDirectory, + _mount: AttachedMount, + _backing: TmpDir, } -impl PreparedTarget { - pub(crate) async fn open( - root: PathBuf, - location: PathBuf, - namespace: Arc, - ) -> Result { - tokio::task::spawn_blocking(move || { - let location = confined_relative(&location)?; - let directory = open_beneath(&root, &location)?; - Ok(Self { - location, - directory, - namespace, - }) - }) - .await - .with_kind(ErrorKind::Unknown)? - } +struct MountSlot { + stage: Option, + placeholder: AttachedMount, } -struct VolumeAttachment { +struct StagedMount { id: SharedVolumeId, readonly: bool, + target: Option, mount: AttachedMount, - _source: TmpMountGuard, + source: PreparedSource, + directory: PathBuf, + path: PathBuf, } -struct AttachmentSlot { - attachment: Option, - placeholder: AttachedMount, +impl StagedMount { + async fn retire(self) -> Result<(), Error> { + if let Some(target) = self.target { + target.detach()?; + drop(target); + } + self.mount.detach()?; + drop(self.mount); + self.source.unmount().await?; + tokio::fs::remove_dir(self.directory).await?; + Ok(()) + } } +/// Revocation detaches SDK-managed targets and stages, including manually managed subcontainers. +/// Independent aliases and open handles remain outside this best-effort boundary. #[derive(Default)] pub struct SharedVolumeMounts { blocked: bool, - slots: BTreeMap<(Guid, PathBuf), AttachmentSlot>, + slots: BTreeMap<(Guid, PathBuf), MountSlot>, + root: Option, } impl SharedVolumeMounts { + /// The caller must establish this root before executing package JavaScript. + pub(crate) async fn new(rootfs: &Path) -> Result { + let backing = TmpDir::new().await?; + tokio::fs::set_permissions(&*backing, std::fs::Permissions::from_mode(0o755)).await?; + std::os::unix::fs::chown(&*backing, Some(0), Some(0))?; + let source = PinnedDirectory::open(&backing, Path::new(""))?; + let target = rootfs.join(SERVICE_ROOT); + tokio::fs::create_dir_all(&target).await?; + let destination = open_beneath(rootfs, Path::new(SERVICE_ROOT))?; + let namespace = Arc::new(MountNamespace::for_process(std::process::id())?); + let mount = AttachedMount::bind(&source, &destination, false, namespace.clone())?; + let directory = PinnedDirectory::open(&target, Path::new(""))?; + let empty = directory.path().join("unavailable"); + tokio::fs::create_dir(&empty).await?; + tokio::fs::set_permissions(&empty, std::fs::Permissions::from_mode(0)).await?; + let empty = open_beneath(directory.path(), Path::new("unavailable"))?; + let unavailable = AttachedMount::bind(&empty, &empty, true, namespace)?; + Ok(Self { + blocked: false, + root: Some(StagingRoot { + _unavailable: unavailable, + directory, + _mount: mount, + _backing: backing, + }), + slots: BTreeMap::new(), + }) + } + pub fn block(&mut self) { self.blocked = true; } - pub fn allow(&mut self) { self.blocked = false; } @@ -197,94 +229,145 @@ impl SharedVolumeMounts { Ok(()) } - pub(crate) async fn prepare( + /// The caller holds the management gate and subcontainer lifetime through mounting. + /// Remounts follow the requested path after parent-directory moves. + pub(crate) async fn prepare_target( &mut self, guid: &Guid, - target: PreparedTarget, - ) -> Result { + location: &Path, + service_root: &Path, + container_root: &Path, + namespace: Arc, + ) -> Result<(), Error> { self.check_allowed()?; - let PreparedTarget { - location, - directory, - namespace, - } = target; - let key = (guid.clone(), location.clone()); + let relative = confined_relative(location)?; + let key = (guid.clone(), relative.clone()); if let Some(slot) = self.slots.get_mut(&key) { - if let Some(attachment) = &slot.attachment { - attachment.mount.detach()?; + if let Some(stage) = slot.stage.take() { + stage.retire().await?; + } + } + let destination = open_beneath(&service_root.join(container_root), &relative)?; + if let Some(slot) = self.slots.get(&key) { + if same_mount(slot.placeholder.mount.as_fd(), destination.as_fd())? { + return Ok(()); } - slot.attachment = None; - } else { - let empty = Path::new(crate::DATA_DIR).join("volume-unavailable"); - tokio::fs::create_dir_all(&empty).await?; - tokio::fs::set_permissions(&empty, std::fs::Permissions::from_mode(0)).await?; - let source = open_beneath(&empty, Path::new(""))?; - let placeholder = AttachedMount::bind(&source, &directory, true, namespace)?; - self.slots.insert( - key, - AttachmentSlot { - attachment: None, - placeholder, - }, - ); } - Ok(location) + self.slots.remove(&key); + let source = open_beneath(service_root, &Path::new(SERVICE_ROOT).join("unavailable"))?; + let placeholder = AttachedMount::bind_in_namespace( + source.as_fd(), + destination.as_fd(), + true, + false, + namespace, + )?; + self.slots.insert( + key, + MountSlot { + placeholder, + stage: None, + }, + ); + Ok(()) } - pub fn attach( + /// Cross-namespace staging supplies the read-only lock; service-owned targets remain detachable. + pub(crate) async fn mount_source( &mut self, guid: &Guid, - location: PathBuf, - id: SharedVolumeId, + location: &Path, + id: &SharedVolumeId, source: PreparedSource, readonly: bool, + service_root: &Path, ) -> Result<(), Error> { self.check_allowed()?; - let slot = self - .slots - .get_mut(&(guid.clone(), location)) - .or_not_found("volume mountpoint")?; + let root = self + .root + .as_ref() + .or_not_found("shared-volume staging root")?; + let key = (guid.clone(), confined_relative(location)?); + let slot = self.slots.get_mut(&key).or_not_found("volume mountpoint")?; + let relative = Path::new(id.as_ref()).join(Guid::new().to_string()); + let path = root.directory.path().join(&relative); + tokio::fs::create_dir_all(&path).await?; + let destination = open_beneath(root.directory.path(), &relative)?; let mount = AttachedMount::bind( &source.directory, - &slot.placeholder.mount, + &destination, readonly, - slot.placeholder.namespace.clone(), + root._mount.namespace.clone(), )?; - slot.attachment = Some(VolumeAttachment { - id, + slot.stage = Some(StagedMount { + id: id.clone(), readonly, mount, - _source: source.guard, + source, + directory: path, + path: Path::new("/").join(SERVICE_ROOT).join(relative), + target: None, }); + let stage = slot.stage.as_mut().unwrap(); + let source = open_beneath(service_root, &confined_relative(&stage.path)?)?; + let namespace = slot.placeholder.namespace.clone(); + stage.target = Some(AttachedMount::bind_in_namespace( + source.as_fd(), + slot.placeholder.mount.as_fd(), + readonly, + true, + namespace, + )?); Ok(()) } - pub fn reconcile_grant( + pub async fn remove_subcontainer(&mut self, guid: &Guid) -> Result<(), Error> { + let keys = self + .slots + .keys() + .filter(|(container, _)| container == guid) + .cloned() + .collect::>(); + let result = self.retire_stages(keys).await; + self.slots.retain(|(container, _), _| container != guid); + result + } + + pub(crate) async fn reconcile_grant( &mut self, - id: &SharedVolumeId, + volume: &SharedVolumeId, grant: Option<&SharedVolumeGrant>, ) -> Result<(), Error> { + let keys = self + .slots + .iter() + .filter(|(_, slot)| { + slot.stage.as_ref().is_some_and(|stage| { + stage.id == *volume && !grant.is_some_and(|grant| grant.allows(stage.readonly)) + }) + }) + .map(|(key, _)| key.clone()) + .collect(); + self.retire_stages(keys).await + } + + async fn retire_stages(&mut self, keys: Vec<(Guid, PathBuf)>) -> Result<(), Error> { let mut errors = ErrorCollection::new(); - for slot in self.slots.values_mut() { - if let Some(attachment) = slot.attachment.as_ref().filter(|attachment| { - &attachment.id == id - && !grant.is_some_and(|grant| attachment.readonly || !grant.readonly) - }) { - if errors.handle(attachment.mount.detach()).is_some() { - slot.attachment = None; - } + for key in keys { + if let Some(stage) = self.slots.get_mut(&key).and_then(|slot| slot.stage.take()) { + errors.handle(stage.retire().await); } } errors.into_result() } - pub fn remove_subcontainer(&mut self, guid: &Guid) { - self.slots.retain(|(container, _), _| container != guid); - } - - pub fn clear(&mut self) { + pub async fn clear(&mut self) -> Result<(), Error> { self.blocked = true; + let result = self + .retire_stages(self.slots.keys().cloned().collect()) + .await; self.slots.clear(); + result } } @@ -306,404 +389,4 @@ pub fn confined_relative(path: &Path) -> Result { } #[cfg(test)] -mod tests { - use super::*; - - #[cfg(target_os = "linux")] - #[tokio::test] - async fn pinned_directory_keeps_identity_after_name_replacement() { - let root = tempfile::tempdir().unwrap(); - let selected = root.path().join("selected"); - std::fs::create_dir(&selected).unwrap(); - std::fs::write(selected.join("marker"), b"original").unwrap(); - let directory = - super::PinnedDirectory::open(root.path(), std::path::Path::new("selected")).unwrap(); - std::fs::rename(&selected, root.path().join("old")).unwrap(); - std::fs::create_dir(&selected).unwrap(); - std::fs::write(selected.join("marker"), b"replacement").unwrap(); - assert_eq!( - tokio::fs::read(directory.path().join("marker")) - .await - .unwrap(), - b"original" - ); - assert_eq!( - std::fs::read(selected.join("marker")).unwrap(), - b"replacement" - ); - } - - #[test] - fn volume_paths_reject_traversal_and_normalize_container_roots() { - assert_eq!( - confined_relative(Path::new("/data/photos")).unwrap(), - Path::new("data/photos") - ); - assert_eq!(confined_relative(Path::new("/")).unwrap(), Path::new("")); - for path in [ - "..", - "../elsewhere", - "/data/../elsewhere", - "data/../../elsewhere", - ] { - assert!(confined_relative(Path::new(path)).is_err()); - } - } - - #[cfg(target_os = "linux")] - #[tokio::test] - async fn prepared_targets_keep_the_pinned_directory_when_renamed() { - use std::os::unix::fs::MetadataExt; - - let root = tempfile::tempdir().unwrap(); - let directory = root.path().join("data"); - std::fs::create_dir(&directory).unwrap(); - let inode = std::fs::metadata(&directory).unwrap().ino(); - let namespace = Arc::new(MountNamespace::for_process(std::process::id()).unwrap()); - let target = PreparedTarget::open(root.path().to_owned(), "/data".into(), namespace) - .await - .unwrap(); - std::fs::rename(&directory, root.path().join("moved")).unwrap(); - std::fs::create_dir(&directory).unwrap(); - assert_eq!(target.location, Path::new("data")); - assert_eq!( - std::fs::File::from(target.directory) - .metadata() - .unwrap() - .ino(), - inode - ); - } - - #[cfg(target_os = "linux")] - #[test] - fn pinned_paths_reject_symlink_and_absolute_escapes() { - use std::os::unix::fs::symlink; - let root = tempfile::tempdir().unwrap(); - let outside = tempfile::tempdir().unwrap(); - std::fs::create_dir(root.path().join("inside")).unwrap(); - symlink(outside.path(), root.path().join("escape")).unwrap(); - symlink("inside", root.path().join("safe")).unwrap(); - assert!(open_beneath(root.path(), Path::new("inside")).is_ok()); - assert!(open_beneath(root.path(), Path::new("safe")).is_ok()); - for path in ["escape", "../", "/etc", "missing"] { - assert!(matches!( - open_beneath(root.path(), Path::new(path)).unwrap_err().kind, - ErrorKind::InvalidRequest - )); - } - } - - #[tokio::test] - #[ignore = "requires root in a private Linux mount namespace"] - async fn real_mounts_enforce_readonly_and_propagate_revocation_without_fallback() { - use std::io::{BufRead, Write}; - use std::process::Stdio; - - use crate::disk::mount::filesystem::ReadWrite; - use crate::disk::mount::filesystem::bind::Bind; - use crate::disk::mount::guard::{GenericMountGuard, MountGuard}; - use crate::util::Invoke; - - let fixture = tempfile::tempdir().unwrap(); - let source_path = fixture.path().join("source"); - let first_root = fixture.path().join("first"); - let second_root = fixture.path().join("second"); - for path in [&source_path, &first_root, &second_root] { - std::fs::create_dir(path).unwrap(); - } - for root in [&first_root, &second_root] { - std::fs::create_dir(root.join("data")).unwrap(); - } - std::fs::create_dir(first_root.join("data2")).unwrap(); - std::fs::write(source_path.join("sentinel"), b"shared").unwrap(); - let first_tree = MountGuard::mount(&Bind::new(&first_root), &first_root, ReadWrite) - .await - .unwrap(); - let second_tree = MountGuard::mount(&Bind::new(&second_root), &second_root, ReadWrite) - .await - .unwrap(); - tokio::process::Command::new("mount") - .arg("--make-rshared") - .arg(&first_root) - .invoke(ErrorKind::Filesystem) - .await - .unwrap(); - let source = TmpMountGuard::mount(&Bind::new(&source_path), ReadWrite) - .await - .unwrap(); - let id = SharedVolumeId::new(); - let first = Guid::new(); - let second = Guid::new(); - let mut mounts = SharedVolumeMounts::default(); - let mut other_service = SharedVolumeMounts::default(); - let namespace = Arc::new(MountNamespace::for_process(std::process::id()).unwrap()); - let target = PreparedTarget::open(first_root.clone(), "/data".into(), namespace.clone()) - .await - .unwrap(); - let pending_target = - PreparedTarget::open(first_root.clone(), "/data".into(), namespace.clone()) - .await - .unwrap(); - for target in [target, pending_target] { - let location = mounts.prepare(&first, target).await.unwrap(); - mounts - .attach( - &first, - location, - id.clone(), - PreparedSource::open(source.clone(), None).await.unwrap(), - false, - ) - .unwrap(); - } - let target = PreparedTarget::open(first_root.clone(), "/data2".into(), namespace.clone()) - .await - .unwrap(); - let location = mounts.prepare(&first, target).await.unwrap(); - mounts - .attach( - &first, - location, - id.clone(), - PreparedSource::open(source.clone(), None).await.unwrap(), - false, - ) - .unwrap(); - let target = PreparedTarget::open(second_root.clone(), "/data".into(), namespace) - .await - .unwrap(); - let location = other_service.prepare(&second, target).await.unwrap(); - other_service - .attach( - &second, - location, - id.clone(), - PreparedSource::open(source.clone(), None).await.unwrap(), - true, - ) - .unwrap(); - assert_eq!( - std::fs::read(first_root.join("data/sentinel")).unwrap(), - b"shared" - ); - assert!(std::fs::write(second_root.join("data/forbidden"), b"no").is_err()); - tokio::process::Command::new("unshare") - .args(["--user", "--map-root-user", "--mount", "sh", "-c"]) - .arg("test -f \"$1/sentinel\" || exit 1; if mount -o remount,bind,rw \"$1\" 2>/dev/null; then exit 1; fi; ! touch \"$1/escalated\" 2>/dev/null") - .arg("sh").arg(second_root.join("data")) - .invoke(ErrorKind::Filesystem).await.unwrap(); - let mut peer = std::process::Command::new("unshare") - .args(["--mount", "--propagation", "slave", "sh", "-c"]) - .arg("test -f \"$1/sentinel\" || exit 1; echo ready; read -r signal; test ! -e \"$1/sentinel\" && ! touch \"$1/fallback\" 2>/dev/null") - .arg("sh").arg(first_root.join("data")) - .stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap(); - let mut ready = String::new(); - std::io::BufReader::new(peer.stdout.take().unwrap()) - .read_line(&mut ready) - .unwrap(); - assert_eq!(ready, "ready\n"); - let failing = (first.clone(), PathBuf::from("data")); - mounts - .slots - .get_mut(&failing) - .unwrap() - .attachment - .as_mut() - .unwrap() - .mount - .fail_detach = true; - assert!(mounts.reconcile_grant(&id, None).is_err()); - assert!(first_root.join("data/sentinel").exists()); - assert!(!first_root.join("data2/sentinel").exists()); - mounts - .slots - .get_mut(&failing) - .unwrap() - .attachment - .as_mut() - .unwrap() - .mount - .fail_detach = false; - mounts.reconcile_grant(&id, None).unwrap(); - peer.stdin.take().unwrap().write_all(b"revoked\n").unwrap(); - assert!(peer.wait().unwrap().success()); - assert!(!first_root.join("data/sentinel").exists()); - assert!(std::fs::write(first_root.join("data/fallback"), b"no").is_err()); - assert_eq!( - std::fs::read(second_root.join("data/sentinel")).unwrap(), - b"shared" - ); - mounts.clear(); - other_service.clear(); - source.unmount().await.unwrap(); - first_tree.unmount(false).await.unwrap(); - second_tree.unmount(false).await.unwrap(); - } - - #[cfg(target_os = "linux")] - #[tokio::test] - #[ignore = "requires root in a private Linux mount namespace"] - async fn old_attachment_teardown_preserves_replacement_with_shared_placeholder_source() { - use crate::disk::mount::filesystem::ReadWrite; - use crate::disk::mount::filesystem::bind::Bind; - use crate::disk::mount::guard::{GenericMountGuard, MountGuard}; - use crate::util::Invoke; - - let fixture = tempfile::tempdir().unwrap(); - let empty = Path::new(crate::DATA_DIR).join("volume-unavailable"); - std::fs::create_dir_all(&empty).unwrap(); - let empty_tree = MountGuard::mount(&Bind::new(&empty), &empty, ReadWrite) - .await - .unwrap(); - tokio::process::Command::new("mount") - .arg("--make-shared") - .arg(&empty) - .invoke(ErrorKind::Filesystem) - .await - .unwrap(); - let namespace = Arc::new(MountNamespace::for_process(std::process::id()).unwrap()); - let mut services = Vec::new(); - let mut sources = Vec::new(); - let mut trees = Vec::new(); - for name in ["old", "replacement"] { - let root = fixture.path().join(name); - let source_path = fixture.path().join(format!("{name}-source")); - std::fs::create_dir_all(root.join("data")).unwrap(); - std::fs::create_dir(&source_path).unwrap(); - std::fs::write(source_path.join("sentinel"), name).unwrap(); - trees.push( - MountGuard::mount(&Bind::new(&root), &root, ReadWrite) - .await - .unwrap(), - ); - let source = TmpMountGuard::mount(&Bind::new(&source_path), ReadWrite) - .await - .unwrap(); - let guid = Guid::new(); - let mut mounts = SharedVolumeMounts::default(); - let target = PreparedTarget::open(root.clone(), "data".into(), namespace.clone()) - .await - .unwrap(); - let location = mounts.prepare(&guid, target).await.unwrap(); - mounts - .attach( - &guid, - location, - SharedVolumeId::new(), - PreparedSource::open(source.clone(), None).await.unwrap(), - false, - ) - .unwrap(); - assert_eq!( - std::fs::read_to_string(root.join("data/sentinel")).unwrap(), - name - ); - services.push(mounts); - sources.push(source); - } - services[0].clear(); - assert_eq!( - std::fs::read_to_string(fixture.path().join("replacement/data/sentinel")).unwrap(), - "replacement" - ); - services[1].clear(); - for source in sources { - source.unmount().await.unwrap(); - } - for tree in trees { - tree.unmount(false).await.unwrap(); - } - empty_tree.unmount(false).await.unwrap(); - } - - #[cfg(target_os = "linux")] - #[tokio::test] - #[ignore = "requires root in a private Linux mount namespace"] - async fn nested_mounts_use_the_service_namespace_and_outlive_its_process() { - use std::io::{BufRead, Write}; - use std::process::Stdio; - - use crate::disk::mount::filesystem::ReadWrite; - use crate::disk::mount::filesystem::bind::Bind; - use crate::disk::mount::guard::GenericMountGuard; - - let fixture = tempfile::tempdir().unwrap(); - let root = fixture.path().join("root"); - let own = fixture.path().join("own"); - let source_path = fixture.path().join("source"); - for path in [root.join("data"), own.clone(), source_path.clone()] { - std::fs::create_dir_all(path).unwrap(); - } - std::fs::write(source_path.join("sentinel"), b"shared").unwrap(); - let mut peer = std::process::Command::new("unshare") - .args(["--mount", "--pid", "--fork", "--mount-proc", "--kill-child", "--propagation", "private", "sh", "-c"]) - .arg("mount --bind \"$1\" \"$2/data\" && mkdir \"$2/data/attached\" || exit 1; echo ready; read -r signal || exit 1; test \"$(cat \"$2/data/attached/sentinel\")\" = shared || exit 1; exec 3<\"$2/data/attached/sentinel\"; echo mounted; read -r signal || exit 1; test ! -e \"$2/data/attached/sentinel\" && ! touch \"$2/data/attached/fallback\" 2>/dev/null && test \"$(cat <&3)\" = shared") - .arg("sh").arg(&own).arg(&root) - .stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap(); - let mut output = std::io::BufReader::new(peer.stdout.take().unwrap()); - let mut line = String::new(); - output.read_line(&mut line).unwrap(); - assert_eq!(line, "ready\n"); - assert!(!root.join("data/attached").exists()); - let namespace = Arc::new(MountNamespace::for_process(peer.id()).unwrap()); - let service_root = PathBuf::from(format!("/proc/{}/root", peer.id())) - .join(root.strip_prefix("/").unwrap()); - let source = TmpMountGuard::mount(&Bind::new(&source_path), ReadWrite) - .await - .unwrap(); - let original_namespace = std::fs::read_link("/proc/thread-self/ns/mnt").unwrap(); - let id = SharedVolumeId::new(); - let guid = Guid::new(); - let mut mounts = SharedVolumeMounts::default(); - let target = PreparedTarget::open(service_root, "data/attached".into(), namespace) - .await - .unwrap(); - let location = mounts.prepare(&guid, target).await.unwrap(); - mounts - .attach( - &guid, - location, - id.clone(), - PreparedSource::open(source.clone(), None).await.unwrap(), - false, - ) - .unwrap(); - peer.stdin - .as_mut() - .unwrap() - .write_all(b"attached\n") - .unwrap(); - line.clear(); - output.read_line(&mut line).unwrap(); - assert_eq!(line, "mounted\n"); - mounts.reconcile_grant(&id, None).unwrap(); - peer.stdin.take().unwrap().write_all(b"revoked\n").unwrap(); - assert!(peer.wait().unwrap().success()); - mounts.clear(); - assert_eq!( - std::fs::read_link("/proc/thread-self/ns/mnt").unwrap(), - original_namespace - ); - assert_eq!( - std::fs::read(source_path.join("sentinel")).unwrap(), - b"shared" - ); - source.unmount().await.unwrap(); - } - - #[test] - fn backup_restore_scope_blocks_mounts_until_explicitly_reenabled() { - let mut mounts = SharedVolumeMounts::default(); - assert!(mounts.check_allowed().is_ok()); - mounts.block(); - assert!(matches!( - mounts.check_allowed().unwrap_err().kind, - ErrorKind::Authorization - )); - mounts.allow(); - assert!(mounts.check_allowed().is_ok()); - mounts.clear(); - assert!(mounts.check_allowed().is_err()); - } -} +mod tests; diff --git a/shared-libs/crates/start-core/src/shared_volumes/mounts/tests.rs b/shared-libs/crates/start-core/src/shared_volumes/mounts/tests.rs new file mode 100644 index 0000000000..183e99d225 --- /dev/null +++ b/shared-libs/crates/start-core/src/shared_volumes/mounts/tests.rs @@ -0,0 +1,416 @@ +use super::*; + +#[cfg(target_os = "linux")] +#[tokio::test] +async fn pinned_directory_keeps_identity_after_name_replacement() { + let root = tempfile::tempdir().unwrap(); + let selected = root.path().join("selected"); + std::fs::create_dir(&selected).unwrap(); + std::fs::write(selected.join("marker"), b"original").unwrap(); + let directory = PinnedDirectory::open(root.path(), Path::new("selected")).unwrap(); + std::fs::rename(&selected, root.path().join("old")).unwrap(); + std::fs::create_dir(&selected).unwrap(); + std::fs::write(selected.join("marker"), b"replacement").unwrap(); + assert_eq!( + tokio::fs::read(directory.path().join("marker")) + .await + .unwrap(), + b"original" + ); + assert_eq!( + std::fs::read(selected.join("marker")).unwrap(), + b"replacement" + ); +} + +#[test] +fn volume_paths_reject_traversal_and_normalize_container_roots() { + assert_eq!( + confined_relative(Path::new("/data/photos")).unwrap(), + Path::new("data/photos") + ); + assert_eq!(confined_relative(Path::new("/")).unwrap(), Path::new("")); + for path in [ + "..", + "../elsewhere", + "/data/../elsewhere", + "data/../../elsewhere", + ] { + assert!(confined_relative(Path::new(path)).is_err()); + } +} + +#[cfg(target_os = "linux")] +#[test] +fn pinned_paths_reject_symlink_and_absolute_escapes() { + use std::os::unix::fs::symlink; + let root = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + std::fs::create_dir(root.path().join("inside")).unwrap(); + symlink(outside.path(), root.path().join("escape")).unwrap(); + symlink("inside", root.path().join("safe")).unwrap(); + assert!(open_beneath(root.path(), Path::new("inside")).is_ok()); + assert!(open_beneath(root.path(), Path::new("safe")).is_ok()); + for path in ["escape", "../", "/etc", "missing"] { + assert!(matches!( + open_beneath(root.path(), Path::new(path)).unwrap_err().kind, + ErrorKind::InvalidRequest + )); + } +} + +#[cfg(target_os = "linux")] +#[test] +fn mount_identity_distinguishes_mounts_not_directories() { + let root = tempfile::tempdir().unwrap(); + std::fs::create_dir(root.path().join("child")).unwrap(); + let parent = open_beneath(root.path(), Path::new("")).unwrap(); + let child = open_beneath(root.path(), Path::new("child")).unwrap(); + let procfs = open_beneath(Path::new("/proc"), Path::new("")).unwrap(); + assert!(same_mount(parent.as_fd(), child.as_fd()).unwrap()); + assert!(!same_mount(parent.as_fd(), procfs.as_fd()).unwrap()); +} + +#[tokio::test] +async fn backup_restore_scope_blocks_staging_until_explicitly_reenabled() { + let mut mounts = SharedVolumeMounts::default(); + assert!(mounts.check_allowed().is_ok()); + mounts.block(); + assert!(mounts.check_allowed().is_err()); + mounts.allow(); + assert!(mounts.check_allowed().is_ok()); + mounts.clear().await.unwrap(); + assert!(mounts.check_allowed().is_err()); +} + +async fn grows(path: &Path, previous: u64) -> u64 { + tokio::time::timeout(std::time::Duration::from_secs(10), async { + loop { + if let Ok(metadata) = tokio::fs::metadata(path).await { + if metadata.len() > previous { + return metadata.len(); + } + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + }) + .await + .expect("container heartbeat did not advance") +} + +async fn prepare_target( + container: &crate::lxc::LxcContainer, + mounts: &mut SharedVolumeMounts, + guid: &Guid, + location: &str, +) -> PathBuf { + container.command(&["mkdir", "-p", location]).await.unwrap(); + let pid = container.pid().await.unwrap(); + let root = PathBuf::from(format!("/proc/{pid}/root")); + let namespace = Arc::new(MountNamespace::for_process(pid).unwrap()); + mounts + .prepare_target(guid, Path::new(location), &root, Path::new(""), namespace) + .await + .unwrap(); + root +} + +async fn mount_managed( + container: &crate::lxc::LxcContainer, + mounts: &Arc>, + guid: &Guid, + location: &str, + id: &SharedVolumeId, + source: &TmpMountGuard, + readonly: bool, +) -> PathBuf { + let mut mounts = mounts.lock().await; + let root = prepare_target(container, &mut mounts, guid, location).await; + mounts + .mount_source( + guid, + Path::new(location), + id, + PreparedSource::open(source.clone(), None).await.unwrap(), + readonly, + &root, + ) + .await + .unwrap(); + PathBuf::from(location) +} + +#[tokio::test] +#[ignore = "requires a StartOS VM, BTRFS_TEST_VOLUMES_DIR and STARTOS_TEST_CONTAINER_HELPER"] +async fn real_lxc_best_effort_revocation_preserves_aliases_and_locks_readonly_stages() { + use crate::disk::mount::filesystem::ReadWrite; + use crate::disk::mount::filesystem::bind::{Bind, FileType}; + use crate::disk::mount::guard::MountGuard; + use crate::lxc::{LxcConfig, LxcManager, service_filesystem}; + + let fixture = crate::util::btrfs::tests::directory(); + std::fs::write(fixture.path().join("sentinel"), b"private data").unwrap(); + std::fs::set_permissions( + fixture.path().join("sentinel"), + std::fs::Permissions::from_mode(0o600), + ) + .unwrap(); + let source = TmpMountGuard::mount( + &service_filesystem(Bind::new(fixture.path()), &[]), + ReadWrite, + ) + .await + .unwrap(); + let manager = Arc::new(LxcManager::new()); + let first = manager.create(None, LxcConfig::default()).await.unwrap(); + let second = manager.create(None, LxcConfig::default()).await.unwrap(); + let helper = std::env::var_os("STARTOS_TEST_CONTAINER_HELPER") + .expect("STARTOS_TEST_CONTAINER_HELPER must name this build's start-container"); + let mut helper_mounts = Vec::new(); + for container in [&first, &second] { + helper_mounts.push( + MountGuard::mount( + &Bind::new(Path::new(&helper)).with_type(FileType::File), + container.rootfs_dir().join("usr/bin/start-container"), + crate::disk::mount::filesystem::ReadOnly, + ) + .await + .unwrap(), + ); + } + let first_mounts = Arc::new(tokio::sync::Mutex::new( + SharedVolumeMounts::new(first.rootfs_dir()).await.unwrap(), + )); + let second_mounts = Arc::new(tokio::sync::Mutex::new( + SharedVolumeMounts::new(second.rootfs_dir()).await.unwrap(), + )); + let registry = crate::shared_volumes::access::SharedVolumeAccess::default(); + let first_package = "first".parse().unwrap(); + registry.register(&first_package, &first_mounts); + registry.register(&"second".parse().unwrap(), &second_mounts); + let id = SharedVolumeId::new(); + let first_guid = Guid::new(); + let second_guid = Guid::new(); + let first_path = mount_managed( + &first, + &first_mounts, + &first_guid, + "/alias", + &id, + &source, + false, + ) + .await; + let second_path = mount_managed( + &second, + &second_mounts, + &second_guid, + "/alias", + &id, + &source, + false, + ) + .await; + let worker = |path: &Path, name: &str| { + format!( + "mkdir /independent; start-container bind-mount --source '{}' --target /independent --recursive; unshare --mount --pid --cgroup --fork sh -c 'exec 3>>/independent/{name}; echo ready >&3; while :; do printf x >&3; sleep 0.02; done' >/dev/null 2>&1 '{0}/nested/marker'", + first_path.display(), + )]).await.unwrap(); + first + .command(&["sh", "-ec", &format!( + "test \"$(cat /alias/nested/marker)\" = nested; mkdir /readonly-tree; start-container bind-mount --source '{}' --target /readonly-tree --recursive --readonly; test \"$(cat /readonly-tree/nested/marker)\" = nested; if touch /readonly-tree/nested/forbidden 2>/dev/null; then exit 110; fi; mkdir '{0}/late-child'; mount -t tmpfs tmpfs '{0}/late-child'; echo late > '{0}/late-child/marker'; test \"$(cat /alias/late-child/marker)\" = late; test ! -e /readonly-tree/late-child/marker", + first_path.display(), + )]) + .await + .unwrap(); + grows(&fixture.path().join("first"), 0).await; + grows(&fixture.path().join("second"), 0).await; + let before = std::fs::metadata(fixture.path().join("first")) + .unwrap() + .len(); + let read_stage = mount_managed( + &first, + &first_mounts, + &first_guid, + "/read", + &id, + &source, + true, + ) + .await; + let unrelated = SharedVolumeId::new(); + let other_stage = mount_managed( + &first, + &first_mounts, + &first_guid, + "/other", + &unrelated, + &source, + false, + ) + .await; + first.command(&["sh", "-ec", "unshare --mount --propagation slave sh -c 'touch /execution-ready; exec sleep 300' >/dev/null 2>&1 & echo $! > /execution-pid; timeout 5 sh -c 'until test -e /execution-ready; do sleep 0.01; done'"]).await.unwrap(); + registry + .reconcile_grant( + &first_package, + &id, + Some(&crate::shared_volumes::SharedVolumeGrant { readonly: true }), + ) + .await + .unwrap(); + first + .command(&[ + "sh", + "-ec", + &format!( + "test ! -e '{}/sentinel'; test ! -e /alias/sentinel; test -r /read/sentinel; test -r /other/sentinel; if mount -o remount,bind,rw /read 2>/dev/null; then exit 109; fi; if touch /alias/forbidden 2>/dev/null; then exit 108; fi; test -r '{}/sentinel'; test -r '{}/sentinel'", + first_path.display(), + read_stage.display(), + other_stage.display(), + ), + ]) + .await.unwrap(); + first.command(&["sh", "-ec", "nsenter --mount=/proc/$(cat /execution-pid)/ns/mnt -- sh -ec 'test ! -e /alias/sentinel; test -r /read/sentinel; test -r /other/sentinel'; kill $(cat /execution-pid)"]).await.unwrap(); + grows(&fixture.path().join("first"), before).await; + registry + .reconcile_grant(&first_package, &id, None) + .await + .unwrap(); + first + .command(&[ + "sh", + "-ec", + &format!( + "test ! -e '{}/sentinel'; test ! -e /read/sentinel; test -r /other/sentinel; test -r '{}/sentinel'", + read_stage.display(), + other_stage.display(), + ), + ]) + .await + .unwrap(); + second + .command(&[ + "sh", + "-ec", + &format!( + "test -r /alias/sentinel; test -r '{}/sentinel'", + second_path.display() + ), + ]) + .await + .unwrap(); + registry.remove_volume(&id).await.unwrap(); + second + .command(&[ + "sh", + "-ec", + &format!( + "test ! -e /alias/sentinel; test ! -e '{}/sentinel'", + second_path.display() + ), + ]) + .await + .unwrap(); + let other = std::fs::metadata(fixture.path().join("second")) + .unwrap() + .len(); + grows(&fixture.path().join("second"), other).await; + + let readonly = mount_managed( + &second, + &second_mounts, + &second_guid, + "/readonly", + &id, + &source, + true, + ) + .await; + let probe = format!( + "set -e; mkdir /readonly-alias; start-container bind-mount --source '{}' --target /readonly-alias --recursive --readonly; test \"$(cat /readonly/sentinel)\" = 'private data'; if mount -o remount,bind,rw /readonly-alias 2>/dev/null; then exit 111; fi; if mount -o remount,bind,rw /readonly 2>/dev/null; then exit 101; fi; if touch /readonly/forbidden 2>/dev/null; then exit 103; fi", + readonly.display(), + ); + second.command(&["sh", "-c", &probe]).await.unwrap(); + mount_managed( + &second, + &second_mounts, + &second_guid, + "/optional", + &id, + &source, + true, + ) + .await; + second + .command(&["sh", "-ec", "test -r /optional/sentinel"]) + .await + .unwrap(); + { + let mut mounts = second_mounts.lock().await; + prepare_target(&second, &mut mounts, &second_guid, "/optional").await; + } + second.command(&["sh", "-ec", "test ! -e /optional/sentinel; if touch /optional/forbidden 2>/dev/null; then exit 107; fi; if mount -o remount,bind,rw /optional 2>/dev/null; then exit 112; fi"]).await.unwrap(); + mount_managed( + &second, + &second_mounts, + &second_guid, + "/optional", + &id, + &source, + true, + ) + .await; + second + .command(&["sh", "-ec", "test -r /optional/sentinel"]) + .await + .unwrap(); + mount_managed( + &first, + &first_mounts, + &first_guid, + "/moving/data", + &id, + &source, + true, + ) + .await; + first + .command(&["sh", "-ec", "mv /moving /moved; mkdir -p /moving/data"]) + .await + .unwrap(); + mount_managed( + &first, + &first_mounts, + &first_guid, + "/moving/data", + &id, + &source, + true, + ) + .await; + first.command(&["sh", "-ec", "test -r /moving/data/sentinel; test ! -e /moved/data/sentinel; if touch /moving/data/forbidden 2>/dev/null; then exit 113; fi"]).await.unwrap(); + assert!(first_mounts.lock().await.check_allowed().is_ok()); + first_mounts.lock().await.clear().await.unwrap(); + second_mounts.lock().await.clear().await.unwrap(); + drop(first_mounts); + drop(second_mounts); + for helper in helper_mounts { + helper.unmount(false).await.unwrap(); + } + first.exit().await.unwrap(); + second.exit().await.unwrap(); + source.unmount().await.unwrap(); +} diff --git a/shared-libs/crates/start-core/src/shared_volumes/source.rs b/shared-libs/crates/start-core/src/shared_volumes/source.rs index 2666a2023e..b3f4bb60f6 100644 --- a/shared-libs/crates/start-core/src/shared_volumes/source.rs +++ b/shared-libs/crates/start-core/src/shared_volumes/source.rs @@ -16,6 +16,9 @@ use crate::shared_volumes::{ SharedVolumeSource, local_path, }; +mod ownership; +pub(crate) use ownership::migrate_local_ownership; + pub async fn create_local_directory(path: &Path) -> Result<(), Error> { tokio::fs::create_dir_all(path.parent().expect("managed volume root")).await?; crate::util::btrfs::create_subvolume(path).await?; @@ -23,11 +26,7 @@ pub async fn create_local_directory(path: &Path) -> Result<(), Error> { } pub(crate) async fn set_local_permissions(path: &Path) -> Result<(), Error> { - std::os::unix::fs::chown( - path, - Some(crate::lxc::BASE_IDMAP.to_id), - Some(crate::lxc::BASE_IDMAP.to_id), - )?; + std::os::unix::fs::chown(path, Some(0), Some(0))?; tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(0o777)).await?; Ok(()) } @@ -118,7 +117,7 @@ impl SourceDefinition { pub(super) fn filesystem(&self, id: &SharedVolumeId) -> SourceFilesystem { match &self.source { SharedVolumeSource::Local => { - SourceFilesystem::Local(local_path(crate::PACKAGE_DATA, id)) + SourceFilesystem::local(local_path(crate::PACKAGE_DATA, id)) } SharedVolumeSource::Disk { logicalname, .. } => SourceFilesystem::external(logicalname), SharedVolumeSource::Cifs { .. } => { @@ -128,36 +127,56 @@ impl SourceDefinition { } } -pub(crate) enum PreparedFilesystem { - Local(PathBuf), +pub(crate) struct LocalSubvolume(pub(crate) PathBuf); + +impl FileSystem for LocalSubvolume { + async fn mount + Send>( + &self, + mountpoint: P, + mount_type: MountType, + ) -> Result<(), Error> { + if !crate::util::btrfs::is_subvolume(&self.0).await { + return Err(Error::new( + eyre!(t!("shared-volumes.source-unavailable")), + ErrorKind::Filesystem, + )); + } + Bind::new(&self.0).mount(mountpoint, mount_type).await + } + + async fn source_hash(&self) -> Result, Error> { + Bind::new(&self.0).source_hash().await + } +} + +pub(crate) enum PreparedFilesystem { + Local(L), Disk(D), Cifs(C), } -pub(super) type SourceFilesystem = PreparedFilesystem>, SharedCifs>; +pub(crate) type SourceFilesystem = + PreparedFilesystem, IdMapped>, SharedCifs>; impl SourceFilesystem { + // Local files retain unshifted owners on disk; service views apply BASE_IDMAP. + pub(crate) fn local(path: PathBuf) -> Self { + Self::Local(crate::lxc::service_filesystem(LocalSubvolume(path), &[])) + } + fn external(device: &Path) -> Self { - Self::Disk(IdMapped::new( + Self::Disk(crate::lxc::service_filesystem( BlockDev::new(device.to_owned()), - vec![crate::lxc::BASE_IDMAP], + &[], )) } } -impl FileSystem for PreparedFilesystem { +impl FileSystem for PreparedFilesystem { async fn mount + Send>( &self, mountpoint: P, mount_type: MountType, ) -> Result<(), Error> { match self { - Self::Local(path) => { - if !crate::util::btrfs::is_subvolume(path).await { - return Err(Error::new( - eyre!(t!("shared-volumes.source-unavailable")), - ErrorKind::Filesystem, - )); - } - Bind::new(path).mount(mountpoint, mount_type).await - } + Self::Local(filesystem) => filesystem.mount(mountpoint, mount_type).await, Self::Disk(filesystem) => filesystem.mount(mountpoint, mount_type).await, Self::Cifs(filesystem) => filesystem.mount(mountpoint, mount_type).await, } @@ -166,19 +185,19 @@ impl FileSystem for PreparedFilesystem { match self { Self::Cifs(filesystem) => filesystem.check_mount(mountpoint).await, Self::Disk(filesystem) => filesystem.check_mount(mountpoint).await, - Self::Local(_) => Ok(()), + Self::Local(filesystem) => filesystem.check_mount(mountpoint).await, } } async fn device(&self) -> Result, Error> { match self { Self::Disk(filesystem) => filesystem.device().await, Self::Cifs(filesystem) => filesystem.device().await, - Self::Local(_) => Ok(None), + Self::Local(filesystem) => filesystem.device().await, } } async fn source_hash(&self) -> Result, Error> { match self { - Self::Local(path) => Bind::new(path).source_hash().await, + Self::Local(filesystem) => filesystem.source_hash().await, Self::Disk(filesystem) => filesystem.source_hash().await, Self::Cifs(filesystem) => filesystem.source_hash().await, } @@ -190,7 +209,7 @@ impl FileSystem for PreparedFilesystem { match self { Self::Cifs(filesystem) => filesystem.mount_hash(mount_type).await, Self::Disk(filesystem) => filesystem.mount_hash(mount_type).await, - Self::Local(path) => Bind::new(path).mount_hash(mount_type).await, + Self::Local(filesystem) => filesystem.mount_hash(mount_type).await, } } } diff --git a/shared-libs/crates/start-core/src/shared_volumes/source/ownership.rs b/shared-libs/crates/start-core/src/shared_volumes/source/ownership.rs new file mode 100644 index 0000000000..ef99ee3842 --- /dev/null +++ b/shared-libs/crates/start-core/src/shared_volumes/source/ownership.rs @@ -0,0 +1,210 @@ +use std::os::unix::fs::MetadataExt; +use std::path::Path; +use std::sync::Arc; + +use super::LocalSubvolume; +use crate::disk::mount::filesystem::ReadOnly; +use crate::disk::mount::guard::{GenericMountGuard, TmpMountGuard}; +use crate::lxc::{BASE_IDMAP, unshifted_filesystem}; +use crate::prelude::*; +use crate::util::btrfs; +use crate::util::io::Counter; + +/// Converts legacy shifted owners before services or observers can mount the root. +/// The caller must exclude mounts and writers throughout recovery and replacement. +pub(crate) async fn migrate_local_ownership(path: &Path) -> Result<(), Error> { + btrfs::recover_conversion(path).await?; + let metadata = match tokio::fs::symlink_metadata(path).await { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error.into()), + }; + let shifted = BASE_IDMAP.to_id..BASE_IDMAP.to_id + BASE_IDMAP.range; + if !metadata.is_dir() + || !(shifted.contains(&metadata.uid()) || shifted.contains(&metadata.gid())) + { + return Ok(()); + } + + let source = TmpMountGuard::mount( + &unshifted_filesystem(LocalSubvolume(path.to_owned())), + ReadOnly, + ) + .await?; + let prepared = btrfs::prepare_conversion( + path, + source.path(), + Arc::new(Counter::new(0, std::sync::atomic::Ordering::Relaxed)), + ) + .await; + let unmounted = source.unmount().await; + prepared?; + unmounted?; + btrfs::commit_conversion(path).await +} + +#[cfg(test)] +mod tests { + use std::os::unix::fs::{MetadataExt, PermissionsExt, symlink}; + + use super::*; + use crate::disk::mount::filesystem::ReadWrite; + use crate::shared_volumes::source::SourceFilesystem; + + #[tokio::test] + async fn current_and_missing_local_roots_need_no_conversion() { + let fixture = tempfile::tempdir().unwrap(); + let path = fixture.path().join("volume"); + migrate_local_ownership(&path).await.unwrap(); + assert!(!path.exists()); + std::fs::create_dir(&path).unwrap(); + std::fs::write(path.join("sentinel"), b"current").unwrap(); + let inode = std::fs::metadata(&path).unwrap().ino(); + migrate_local_ownership(&path).await.unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().ino(), inode); + assert_eq!(std::fs::read(path.join("sentinel")).unwrap(), b"current"); + } + + fn acl(user: u32) -> Vec { + let mut acl = 2u32.to_le_bytes().to_vec(); + for (tag, permission, id) in [ + (0x01u16, 7u16, u32::MAX), + (0x02, 4, user), + (0x04, 5, u32::MAX), + (0x10, 5, u32::MAX), + (0x20, 0, u32::MAX), + ] { + acl.extend_from_slice(&tag.to_le_bytes()); + acl.extend_from_slice(&permission.to_le_bytes()); + acl.extend_from_slice(&id.to_le_bytes()); + } + acl + } + + async fn legacy(path: &Path) { + btrfs::create_subvolume(path).await.unwrap(); + std::fs::write(path.join("sentinel"), b"existing data").unwrap(); + std::os::unix::fs::chown(path, Some(100000), Some(100000)).unwrap(); + std::os::unix::fs::chown(path.join("sentinel"), Some(101000), Some(102000)).unwrap(); + std::fs::set_permissions( + path.join("sentinel"), + std::fs::Permissions::from_mode(0o6750), + ) + .unwrap(); + std::fs::hard_link(path.join("sentinel"), path.join("hardlink")).unwrap(); + symlink("sentinel", path.join("symlink")).unwrap(); + std::os::unix::fs::lchown(path.join("symlink"), Some(100123), Some(100456)).unwrap(); + xattr::set(path.join("sentinel"), "user.migration", b"retained").unwrap(); + xattr::set( + path.join("sentinel"), + "system.posix_acl_access", + &acl(100123), + ) + .unwrap(); + let executable = path.join("executable"); + std::fs::write(&executable, b"executable").unwrap(); + std::os::unix::fs::chown(&executable, Some(101000), Some(102000)).unwrap(); + xattr::set( + &executable, + "security.capability", + &[ + 1, 0, 0, 3, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 160, 134, 1, 0, + ], + ) + .unwrap(); + xattr::set(path, "system.posix_acl_default", &acl(100123)).unwrap(); + } + + #[tokio::test] + #[ignore = "requires root, BTRFS_TEST_VOLUMES_DIR and a private Linux mount namespace"] + async fn legacy_local_ownership_is_replaced_once_without_losing_metadata() { + let fixture = btrfs::tests::directory(); + let path = fixture.path().join("volume"); + legacy(&path).await; + migrate_local_ownership(&path).await.unwrap(); + let root = std::fs::metadata(&path).unwrap(); + assert_eq!((root.uid(), root.gid()), (0, 0)); + let file = std::fs::metadata(path.join("sentinel")).unwrap(); + assert_eq!( + (file.uid(), file.gid(), file.mode() & 0o7777), + (1000, 2000, 0o6750) + ); + assert_eq!( + std::fs::read(path.join("sentinel")).unwrap(), + b"existing data" + ); + assert_eq!( + file.ino(), + std::fs::metadata(path.join("hardlink")).unwrap().ino() + ); + assert_eq!( + std::fs::read_link(path.join("symlink")).unwrap(), + Path::new("sentinel") + ); + let link = std::fs::symlink_metadata(path.join("symlink")).unwrap(); + assert_eq!((link.uid(), link.gid()), (123, 456)); + assert_eq!( + xattr::get(path.join("sentinel"), "user.migration") + .unwrap() + .unwrap(), + b"retained" + ); + assert_eq!( + xattr::get(path.join("sentinel"), "system.posix_acl_access").unwrap(), + Some(acl(123)) + ); + assert_eq!( + xattr::get(&path, "system.posix_acl_default").unwrap(), + Some(acl(123)) + ); + assert_eq!( + xattr::get(path.join("executable"), "system.posix_acl_access").unwrap(), + None + ); + assert_eq!( + xattr::get(path.join("executable"), "security.capability").unwrap(), + Some(vec![ + 1, 0, 0, 2, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]) + ); + let view = TmpMountGuard::mount(&SourceFilesystem::local(path.clone()), ReadWrite) + .await + .unwrap(); + let visible = std::fs::metadata(view.path().join("sentinel")).unwrap(); + assert_eq!((visible.uid(), visible.gid()), (101000, 102000)); + view.unmount().await.unwrap(); + let retired = fixture.path().join("volume.convert-old"); + legacy(&retired).await; + migrate_local_ownership(&path).await.unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().ino(), root.ino()); + assert!(!retired.exists()); + } + + #[tokio::test] + #[ignore = "requires root, BTRFS_TEST_VOLUMES_DIR and a private Linux mount namespace"] + async fn interrupted_ownership_conversion_recovers_before_mounting() { + for moved in [false, true] { + let fixture = btrfs::tests::directory(); + let path = fixture.path().join("volume"); + legacy(&path).await; + let temporary = fixture.path().join("volume.convert-tmp"); + btrfs::create_subvolume(&temporary).await.unwrap(); + std::fs::write(temporary.join("incomplete"), b"not published").unwrap(); + if moved { + std::fs::rename(&path, fixture.path().join("volume.convert-old")).unwrap(); + } + migrate_local_ownership(&path).await.unwrap(); + assert_eq!( + std::fs::read(path.join("sentinel")).unwrap(), + b"existing data" + ); + assert_eq!( + std::fs::metadata(path.join("sentinel")).unwrap().uid(), + 1000 + ); + assert!(!path.join("incomplete").exists()); + assert!(!temporary.exists()); + assert!(!fixture.path().join("volume.convert-old").exists()); + } + } +} diff --git a/shared-libs/crates/start-core/src/shared_volumes/source/tests.rs b/shared-libs/crates/start-core/src/shared_volumes/source/tests.rs index c43e55a687..726d9cf010 100644 --- a/shared-libs/crates/start-core/src/shared_volumes/source/tests.rs +++ b/shared-libs/crates/start-core/src/shared_volumes/source/tests.rs @@ -1,14 +1,23 @@ use super::*; -#[test] -fn local_filesystem_uses_persisted_package_data_partition() { +#[tokio::test] +async fn local_sources_apply_the_base_map_and_keep_raw_backup_targets_separate() { let id = SharedVolumeId::new(); let definition = SourceDefinition::new(SharedVolumeSource::Local, None); - let PreparedFilesystem::Local(path) = definition.filesystem(&id) else { - panic!("local filesystem") - }; - assert!(path.starts_with(crate::PACKAGE_DATA)); - assert!(path.ends_with(Path::new("shared-volumes").join(id.as_ref()))); + let path = local_path(crate::PACKAGE_DATA, &id); + let mapped = definition.filesystem(&id); + let expected = IdMapped::new(Bind::new(&path), vec![crate::lxc::BASE_IDMAP]); + assert_eq!( + mapped.source_hash().await.unwrap(), + expected.source_hash().await.unwrap() + ); + let raw = PreparedFilesystem::<_, BlockDev, Cifs>::Local(LocalSubvolume(path)); + for access in [ReadOnly, ReadWrite] { + assert_ne!( + mapped.mount_hash(access).await.unwrap(), + raw.mount_hash(access).await.unwrap() + ); + } } #[tokio::test] @@ -42,19 +51,31 @@ async fn failed_publications_remove_new_directories_and_successful_ones_preserve } #[tokio::test] -#[ignore = "requires BTRFS_TEST_VOLUMES_DIR and UID/GID 100000 mapped"] -async fn local_creation_uses_service_owned_subvolumes_and_rolls_back_failed_publication() { +#[ignore = "requires root, BTRFS_TEST_VOLUMES_DIR and a private Linux mount namespace"] +async fn local_creation_maps_owners_without_shifting_persisted_ids() { use std::os::unix::fs::{MetadataExt, PermissionsExt}; let fixture = crate::util::btrfs::tests::directory(); let path = fixture.path().join("volume"); create_local_directory(&path).await.unwrap(); assert!(crate::util::btrfs::is_subvolume(&path).await); let metadata = std::fs::metadata(&path).unwrap(); - assert_eq!( - (metadata.uid(), metadata.gid()), - (crate::lxc::BASE_IDMAP.to_id, crate::lxc::BASE_IDMAP.to_id) - ); + assert_eq!((metadata.uid(), metadata.gid()), (0, 0)); assert_eq!(metadata.permissions().mode() & 0o777, 0o777); + let file = path.join("owner"); + std::fs::write(&file, b"data").unwrap(); + std::os::unix::fs::chown(&file, Some(1000), Some(2000)).unwrap(); + let view = TmpMountGuard::mount(&SourceFilesystem::local(path.clone()), ReadWrite) + .await + .unwrap(); + let root = std::fs::metadata(view.path()).unwrap(); + assert_eq!((root.uid(), root.gid()), (100000, 100000)); + let mapped_file = view.path().join("owner"); + let metadata = std::fs::metadata(&mapped_file).unwrap(); + assert_eq!((metadata.uid(), metadata.gid()), (101000, 102000)); + std::os::unix::fs::chown(&mapped_file, Some(103000), Some(104000)).unwrap(); + let metadata = std::fs::metadata(&file).unwrap(); + assert_eq!((metadata.uid(), metadata.gid()), (3000, 4000)); + view.unmount().await.unwrap(); tokio::fs::write(path.join("sentinel"), b"allocated data") .await .unwrap(); @@ -319,13 +340,12 @@ async fn checking_a_missing_local_directory_does_not_recreate_it() { let path = root.path().join("removed"); let target = root.path().join("mountpoint"); assert!( - SourceFilesystem::Local(path.clone()) + SourceFilesystem::local(path.clone()) .mount(&target, ReadWrite) .await .is_err() ); assert!(!path.exists()); - assert!(!target.exists()); } #[test] diff --git a/shared-libs/crates/start-core/src/util/actor/concurrent.rs b/shared-libs/crates/start-core/src/util/actor/concurrent.rs index cce7b691bb..56003703c1 100644 --- a/shared-libs/crates/start-core/src/util/actor/concurrent.rs +++ b/shared-libs/crates/start-core/src/util/actor/concurrent.rs @@ -1,9 +1,8 @@ use std::any::Any; use std::sync::Arc; -use std::time::Duration; -use futures::future::{BoxFuture, ready}; -use futures::{Future, FutureExt, TryFutureExt}; +use futures::future::BoxFuture; +use futures::{Future, FutureExt}; use tokio::sync::{mpsc, oneshot}; use crate::prelude::*; @@ -36,6 +35,7 @@ impl Future for ConcurrentRunner { cx: &mut std::task::Context<'_>, ) -> std::task::Poll { let mut this = self.project(); + let was_accepting = this.shutdown.is_some(); *this.shutdown = this.shutdown.take().and_then(|mut s| { if s.poll_unpin(cx).is_pending() { Some(s) @@ -43,6 +43,10 @@ impl Future for ConcurrentRunner { None } }); + if was_accepting && this.shutdown.is_none() { + this.waiting.clear(); + this.recv.close(); + } if this.shutdown.is_some() { while let std::task::Poll::Ready(Some((id, msg, reply))) = this.recv.poll_recv(cx) { if this @@ -172,7 +176,7 @@ impl ConcurrentActor { } } - /// Message is guaranteed to be queued immediately + /// Enqueues before the returned future is polled. pub fn queue( &self, id: Guid, @@ -181,32 +185,7 @@ impl ConcurrentActor { where A: Handler, { - if self.runtime.is_finished() { - return futures::future::Either::Left(ready(Err(Error::new( - eyre!("actor runtime has exited"), - ErrorKind::Unknown, - )))); - } - let (reply_send, reply_recv) = oneshot::channel(); - self.messenger - .send((id, Box::new(message), reply_send)) - .unwrap(); - futures::future::Either::Right( - reply_recv - .map_err(|_| Error::new(eyre!("actor runtime has exited"), ErrorKind::Unknown)) - .and_then(|a| { - ready( - a.downcast() - .map_err(|_| { - Error::new( - eyre!("received incorrect type in response"), - ErrorKind::Incoherent, - ) - }) - .map(|a| *a), - ) - }), - ) + super::enqueue(&self.messenger, id, message) } pub async fn send(&self, id: Guid, message: M) -> Result @@ -218,31 +197,7 @@ impl ConcurrentActor { pub async fn shutdown(self, strategy: PendingMessageStrategy) { drop(self.messenger); - let timeout = match strategy { - PendingMessageStrategy::CancelAll => { - self.shutdown.send(()).unwrap(); - Some(Duration::from_secs(0)) - } - PendingMessageStrategy::FinishCurrentCancelPending { timeout } => { - self.shutdown.send(()).unwrap(); - timeout - } - PendingMessageStrategy::FinishAll { timeout } => timeout, - }; - let aborter = if let Some(timeout) = timeout { - let hdl = self.runtime.abort_handle(); - async move { - tokio::time::sleep(timeout).await; - hdl.abort(); - } - .boxed() - } else { - futures::future::pending().boxed() - }; - tokio::select! { - _ = aborter => (), - _ = self.runtime => (), - } + super::shutdown_runtime(self.runtime, self.shutdown, strategy).await; } } @@ -297,6 +252,135 @@ mod test { ) -> Self::Response { } } + struct HoldResources { + resource: std::sync::Arc<()>, + started: tokio::sync::oneshot::Sender<()>, + background_started: tokio::sync::oneshot::Sender<()>, + } + impl Handler for CActor { + type Response = (); + fn conflicts_with(_: &HoldResources) -> ConflictBuilder { + ConflictBuilder::nothing() + } + async fn handle( + &mut self, + _: Guid, + message: HoldResources, + jobs: &BackgroundJobQueue, + ) -> Self::Response { + let background = message.resource.clone(); + jobs.add_job(async move { + let _held = background; + message.background_started.send(()).unwrap(); + futures::future::pending::<()>().await; + }); + message.started.send(()).unwrap(); + let _held = message.resource; + futures::future::pending().await + } + } + + async fn held_resources(enqueue: impl FnOnce(HoldResources)) -> std::sync::Arc<()> { + let resource = std::sync::Arc::new(()); + let (started, ready) = tokio::sync::oneshot::channel(); + let (background_started, background_ready) = tokio::sync::oneshot::channel(); + enqueue(HoldResources { + resource: resource.clone(), + started, + background_started, + }); + ready.await.unwrap(); + background_ready.await.unwrap(); + assert_eq!(std::sync::Arc::strong_count(&resource), 3); + resource + } + + async fn holding_actor() -> (super::ConcurrentActor, std::sync::Arc<()>) { + let actor = super::ConcurrentActor::new(CActor); + let resource = held_resources(|message| drop(actor.queue(Guid::new(), message))).await; + (actor, resource) + } + + #[tokio::test] + async fn cancel_all_shutdown_joins_resource_release() { + let (actor, resource) = holding_actor().await; + actor + .shutdown(crate::util::actor::PendingMessageStrategy::CancelAll) + .await; + assert_eq!(std::sync::Arc::strong_count(&resource), 1); + } + + #[tokio::test] + async fn simple_actor_cancel_all_joins_resource_release() { + let actor = crate::util::actor::simple::SimpleActor::new(CActor); + let resource = held_resources(|message| drop(actor.queue(message))).await; + actor + .shutdown(crate::util::actor::PendingMessageStrategy::CancelAll) + .await; + assert_eq!(std::sync::Arc::strong_count(&resource), 1); + } + + #[tokio::test] + async fn stopped_actor_rejects_admission_without_panicking() { + let mut actor = super::ConcurrentActor::new(CActor); + actor.runtime.abort(); + let _ = (&mut actor.runtime).await; + assert!(actor.send(Guid::new(), NoConflicts).await.is_err()); + } + + struct AwaitRelease { + started: tokio::sync::oneshot::Sender<()>, + release: tokio::sync::oneshot::Receiver<()>, + } + impl Handler for CActor { + type Response = (); + fn conflicts_with(_: &AwaitRelease) -> ConflictBuilder { + ConflictBuilder::everything().except::() + } + async fn handle(&mut self, _: Guid, message: AwaitRelease, _: &BackgroundJobQueue) { + message.started.send(()).unwrap(); + message.release.await.unwrap(); + } + } + struct TrackWork(std::sync::Arc); + impl Handler for CActor { + type Response = (); + async fn handle(&mut self, _: Guid, message: TrackWork, _: &BackgroundJobQueue) { + message.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } + } + + #[tokio::test] + async fn finish_current_discards_waiting_messages_without_a_timeout() { + let actor = super::ConcurrentActor::new(CActor); + let (started, ready) = tokio::sync::oneshot::channel(); + let (release, released) = tokio::sync::oneshot::channel(); + drop(actor.queue( + Guid::new(), + AwaitRelease { + started, + release: released, + }, + )); + ready.await.unwrap(); + let pending = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + drop(actor.queue(Guid::new(), TrackWork(pending.clone()))); + actor.send(Guid::new(), NoConflicts).await.unwrap(); + let shutdown = actor.shutdown( + crate::util::actor::PendingMessageStrategy::FinishCurrentCancelPending { + timeout: None, + }, + ); + let (result, ()) = tokio::join!( + tokio::time::timeout(Duration::from_secs(2), shutdown), + async { + release.send(()).unwrap(); + }, + ); + result.unwrap(); + assert_eq!(pending.load(std::sync::atomic::Ordering::SeqCst), 0); + } + #[tokio::test] async fn test_conflicts() { let actor = super::ConcurrentActor::new(CActor); diff --git a/shared-libs/crates/start-core/src/util/actor/mod.rs b/shared-libs/crates/start-core/src/util/actor/mod.rs index 0787e61e77..bfc227ebc2 100644 --- a/shared-libs/crates/start-core/src/util/actor/mod.rs +++ b/shared-libs/crates/start-core/src/util/actor/mod.rs @@ -5,12 +5,12 @@ use std::time::Duration; use futures::future::BoxFuture; use futures::{Future, FutureExt}; -use tokio::sync::oneshot; +use tokio::sync::{mpsc, oneshot}; -#[allow(unused_imports)] use crate::prelude::*; use crate::rpc_continuations::Guid; use crate::util::actor::background::BackgroundJobQueue; +use crate::util::future::NonDetachingJoinHandle; pub mod background; pub mod concurrent; @@ -23,7 +23,7 @@ pub trait Actor: Sized + Send + 'static { pub trait Handler: Actor { type Response: Any + Send; - /// DRAGONS: this must be correctly implemented bi-directionally in order to work as expected + /// Conflict decisions must be symmetric. fn conflicts_with(#[allow(unused_variables)] msg: &M) -> ConflictBuilder { ConflictBuilder::everything() } @@ -93,6 +93,63 @@ type Request = ( oneshot::Sender>, ); +fn runtime_exited() -> Error { + Error::new(eyre!(t!("util.actor.runtime-exited")), ErrorKind::Unknown) +} + +fn enqueue, M: Send + 'static>( + messenger: &mpsc::UnboundedSender>, + id: Guid, + message: M, +) -> impl Future> { + let (reply, response) = oneshot::channel(); + if messenger.send((id, Box::new(message), reply)).is_err() { + return futures::future::Either::Left(futures::future::ready(Err(runtime_exited()))); + } + futures::future::Either::Right(async move { + response + .await + .map_err(|_| runtime_exited())? + .downcast() + .map(|value| *value) + .map_err(|_| { + Error::new( + eyre!("received incorrect type in response"), + ErrorKind::Incoherent, + ) + }) + }) +} + +fn shutdown_runtime( + mut runtime: NonDetachingJoinHandle<()>, + shutdown: oneshot::Sender<()>, + strategy: PendingMessageStrategy, +) -> BoxFuture<'static, ()> { + async move { + let timeout = match strategy { + PendingMessageStrategy::CancelAll => { + let _ = runtime.wait_for_abort().await; + return; + } + PendingMessageStrategy::FinishCurrentCancelPending { timeout } => { + let _ = shutdown.send(()); + timeout + } + PendingMessageStrategy::FinishAll { timeout } => timeout, + }; + if let Some(timeout) = timeout { + if tokio::time::timeout(timeout, &mut runtime).await.is_err() { + let _ = runtime.wait_for_abort().await; + } + } else { + let _ = runtime.await; + } + } + .boxed() +} + +/// Shutdown always joins the runner, including cancellation. pub enum PendingMessageStrategy { CancelAll, FinishCurrentCancelPending { timeout: Option }, diff --git a/shared-libs/crates/start-core/src/util/actor/simple.rs b/shared-libs/crates/start-core/src/util/actor/simple.rs index 663a1a3bde..461889a024 100644 --- a/shared-libs/crates/start-core/src/util/actor/simple.rs +++ b/shared-libs/crates/start-core/src/util/actor/simple.rs @@ -1,7 +1,4 @@ -use std::time::Duration; - -use futures::future::ready; -use futures::{Future, FutureExt, TryFutureExt}; +use futures::Future; use tokio::sync::oneshot::error::TryRecvError; use tokio::sync::{mpsc, oneshot}; @@ -45,7 +42,7 @@ impl SimpleActor { } } - /// Message is guaranteed to be queued immediately + /// Enqueues before the returned future is polled. pub fn queue( &self, message: M, @@ -53,32 +50,7 @@ impl SimpleActor { where A: Handler, { - if self.runtime.is_finished() { - return futures::future::Either::Left(ready(Err(Error::new( - eyre!("actor runtime has exited"), - ErrorKind::Unknown, - )))); - } - let (reply_send, reply_recv) = oneshot::channel(); - self.messenger - .send((Guid::new(), Box::new(message), reply_send)) - .unwrap(); - futures::future::Either::Right( - reply_recv - .map_err(|_| Error::new(eyre!("actor runtime has exited"), ErrorKind::Unknown)) - .and_then(|a| { - ready( - a.downcast() - .map_err(|_| { - Error::new( - eyre!("received incorrect type in response"), - ErrorKind::Incoherent, - ) - }) - .map(|a| *a), - ) - }), - ) + super::enqueue(&self.messenger, Guid::new(), message) } pub async fn send(&self, message: M) -> Result @@ -90,30 +62,6 @@ impl SimpleActor { pub async fn shutdown(self, strategy: PendingMessageStrategy) { drop(self.messenger); - let timeout = match strategy { - PendingMessageStrategy::CancelAll => { - self.shutdown.send(()).unwrap(); - Some(Duration::from_secs(0)) - } - PendingMessageStrategy::FinishCurrentCancelPending { timeout } => { - self.shutdown.send(()).unwrap(); - timeout - } - PendingMessageStrategy::FinishAll { timeout } => timeout, - }; - let aborter = if let Some(timeout) = timeout { - let hdl = self.runtime.abort_handle(); - async move { - tokio::time::sleep(timeout).await; - hdl.abort(); - } - .boxed() - } else { - futures::future::pending().boxed() - }; - tokio::select! { - _ = aborter => (), - _ = self.runtime => (), - } + super::shutdown_runtime(self.runtime, self.shutdown, strategy).await; } } diff --git a/shared-libs/crates/start-core/src/util/btrfs.rs b/shared-libs/crates/start-core/src/util/btrfs.rs index a2244bb15a..57a4e6a464 100644 --- a/shared-libs/crates/start-core/src/util/btrfs.rs +++ b/shared-libs/crates/start-core/src/util/btrfs.rs @@ -129,12 +129,27 @@ pub(crate) async fn convert_directory( if !tokio::fs::try_exists(path).await? || is_subvolume(path).await { return Ok(()); } - let (temporary, original) = conversion_paths(path); + prepare_conversion(path, path, counter).await?; + commit_conversion(path).await +} + +pub(crate) async fn prepare_conversion( + path: &Path, + source: &Path, + counter: std::sync::Arc, +) -> Result<(), Error> { + let (temporary, _) = conversion_paths(path); create_subvolume(&temporary).await?; - if let Err(error) = crate::util::clone::clone_tree(path, &temporary, counter).await { + if let Err(error) = crate::util::clone::clone_tree(source, &temporary, counter).await { delete_tree(&temporary).await.log_err(); return Err(error); } + crate::disk::mount::util::sync_filesystem(&temporary).await +} + +/// Publishes a prepared replacement; the caller must exclude mounts and writers. +pub(crate) async fn commit_conversion(path: &Path) -> Result<(), Error> { + let (temporary, original) = conversion_paths(path); if let Err(error) = crate::util::io::rename(path, &original).await { delete_tree(&temporary).await.log_err(); return Err(error); @@ -144,5 +159,6 @@ pub(crate) async fn convert_directory( delete_tree(&temporary).await.log_err(); return Err(error); } + crate::disk::mount::util::sync_filesystem(path).await?; delete_tree(&original).await } diff --git a/shared-libs/crates/start-core/src/util/clone.rs b/shared-libs/crates/start-core/src/util/clone.rs index 00b767e6fd..32f62f4f30 100644 --- a/shared-libs/crates/start-core/src/util/clone.rs +++ b/shared-libs/crates/start-core/src/util/clone.rs @@ -66,11 +66,9 @@ mod linux { use crate::util::io::Counter; - /// Clone granularity for regular files. Must be a multiple of the - /// filesystem block size so every chunk boundary is FICLONERANGE-aligned. + // Must align to filesystem blocks for FICLONERANGE. const CHUNK: u64 = 1 << 30; - /// FS_NOCOW_FL from linux/fs.h; libc does not export the FS_*_FL family. const FS_NOCOW_FL: libc::c_long = 0x0080_0000; pub struct Cloner { @@ -84,10 +82,27 @@ mod linux { if !dst.is_dir() { std::fs::create_dir(dst)?; } - copy_dir_flags(src, dst)?; - copy_xattrs_nofollow(src, dst)?; + self.clone_directory(src, dst, &meta) + } + + // Cloned children must not acquire ACL entries absent from the source. + fn clone_directory( + &mut self, + src: &Path, + dst: &Path, + meta: &std::fs::Metadata, + ) -> std::io::Result<()> { + mirror_directory_nocow(src, dst)?; + for name in ["system.posix_acl_access", "system.posix_acl_default"] { + if let Err(error) = ::xattr::remove(dst, name) { + if !matches!(error.raw_os_error(), Some(libc::ENODATA | libc::ENOTSUP)) { + return Err(error); + } + } + } self.clone_dir_contents(src, dst)?; - apply_dir_metadata(dst, &meta) + apply_dir_metadata(dst, meta)?; + copy_xattrs_nofollow(src, dst) } fn clone_dir_contents(&mut self, src: &Path, dst: &Path) -> std::io::Result<()> { @@ -99,10 +114,7 @@ mod linux { let ft = meta.file_type(); if ft.is_dir() { std::fs::create_dir(&dst_path)?; - copy_dir_flags(&src_path, &dst_path)?; - copy_xattrs_nofollow(&src_path, &dst_path)?; - self.clone_dir_contents(&src_path, &dst_path)?; - apply_dir_metadata(&dst_path, &meta)?; + self.clone_directory(&src_path, &dst_path, &meta)?; } else if ft.is_file() { if meta.nlink() > 1 { if let Some(existing) = self.hardlinks.get(&(meta.dev(), meta.ino())) { @@ -151,11 +163,7 @@ mod linux { .create_new(true) .mode(meta.mode() & 0o777) .open(dst)?; - // Flags must match before cloning: btrfs returns EINVAL for a - // clone between nodatacow and datacow inodes, and +C only sticks - // while the destination has no extents. Mirror exactly — the - // destination may have inherited +C from its parent dir even when - // the source file is datacow. + // Btrfs requires matching +C before the destination acquires extents. mirror_nocow(&src_f, &dst_f)?; let size = meta.len(); let mut offset = 0u64; @@ -165,9 +173,10 @@ mod linux { self.ctr.add(len); offset += len; } - copy_xattrs(&src_f, &dst_f)?; + // Ownership changes clear file capabilities. fchown(&dst_f, Some(meta.uid()), Some(meta.gid()))?; dst_f.set_permissions(PermissionsExt::from_mode(meta.mode() & 0o7777))?; + copy_xattrs(&src_f, &dst_f)?; set_times(&dst_f, meta) } } @@ -209,9 +218,7 @@ mod linux { Ok(()) } - /// Mirrors +C on a directory so files created inside inherit it, matching - /// the source's inheritance behavior. - fn copy_dir_flags(src: &Path, dst: &Path) -> std::io::Result<()> { + fn mirror_directory_nocow(src: &Path, dst: &Path) -> std::io::Result<()> { mirror_nocow(&File::open(src)?, &File::open(dst)?) } @@ -478,6 +485,32 @@ mod linux { assert_eq!(progress.load(), 5); } + #[tokio::test] + #[ignore = "requires root and BTRFS_TEST_VOLUMES_DIR"] + async fn clones_capabilities_after_restoring_file_ownership() { + let fixture = crate::util::btrfs::tests::directory(); + let src = fixture.path().join("src"); + let dst = fixture.path().join("dst"); + std::fs::create_dir(&src).unwrap(); + let file = src.join("file"); + std::fs::write(&file, b"executable").unwrap(); + std::os::unix::fs::chown(&file, Some(1000), Some(2000)).unwrap(); + ::xattr::set( + &file, + "security.capability", + &[1, 0, 0, 2, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ) + .unwrap(); + let capabilities = xattr(&file, "security.capability").unwrap(); + clone_tree(&src, &dst, ctr()).await.unwrap(); + assert_eq!( + xattr(&dst.join("file"), "security.capability"), + Some(capabilities) + ); + let metadata = std::fs::metadata(dst.join("file")).unwrap(); + assert_eq!((metadata.uid(), metadata.gid()), (1000, 2000)); + } + #[tokio::test] async fn clones_symlinks_and_fifos() { let tmp = TestDir::new("special"); diff --git a/shared-libs/crates/start-core/src/util/future.rs b/shared-libs/crates/start-core/src/util/future.rs index d5794cac58..ad709de143 100644 --- a/shared-libs/crates/start-core/src/util/future.rs +++ b/shared-libs/crates/start-core/src/util/future.rs @@ -85,21 +85,30 @@ async fn test_detach_inside_own_task() { assert!(!survives(false).await); } -#[pin_project::pin_project(PinnedDrop)] +struct DropSignal(watch::Sender); + +impl Drop for DropSignal { + fn drop(&mut self) { + let _ = self.0.send(true); + } +} + +#[pin_project::pin_project] pub struct DropSignaling { #[pin] fut: F, - on_drop: watch::Sender, + // Must follow the future; field drop order defines completion. + on_drop: DropSignal, } impl DropSignaling { pub fn new(fut: F) -> Self { Self { fut, - on_drop: watch::channel(false).0, + on_drop: DropSignal(watch::channel(false).0), } } pub fn subscribe(&self) -> DropHandle { - DropHandle(self.on_drop.subscribe()) + DropHandle(self.on_drop.0.subscribe()) } } impl Future for DropSignaling @@ -112,11 +121,28 @@ where this.fut.poll(cx) } } -#[pin_project::pinned_drop] -impl PinnedDrop for DropSignaling { - fn drop(self: Pin<&mut Self>) { - let _ = self.on_drop.send(true); + +#[tokio::test] +async fn drop_completion_follows_inner_resource_cleanup() { + struct Probe(std::sync::Arc>>); + impl Future for Probe { + type Output = (); + fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<()> { + Poll::Pending + } + } + impl Drop for Probe { + fn drop(&mut self) { + assert!(!*self.0.lock().unwrap().as_ref().unwrap().0.borrow()); + } } + let observer = std::sync::Arc::new(std::sync::Mutex::new(None)); + let future = DropSignaling::new(Probe(observer.clone())); + let mut completion = future.subscribe(); + *observer.lock().unwrap() = Some(completion.clone()); + drop(future); + completion.wait().await; + assert!(*completion.0.borrow()); } #[derive(Clone)] diff --git a/shared-libs/ts-modules/start-core/lib/Effects.ts b/shared-libs/ts-modules/start-core/lib/Effects.ts index f8d5cf2c28..367e73be63 100644 --- a/shared-libs/ts-modules/start-core/lib/Effects.ts +++ b/shared-libs/ts-modules/start-core/lib/Effects.ts @@ -121,7 +121,7 @@ export type Effects = { getSharedVolumes(options: { callback?: () => void }): Promise> - /** Mount a granted shared volume. Authorization and invalid-path failures reject. */ + /** Mounts and tracks user-granted storage; authorization and invalid paths reject. */ mountSharedVolume( options: RPC.RpcParamType, ): Promise> From 781d7930e3ea4af537b478da03023e565ccaebb7 Mon Sep 17 00:00:00 2001 From: Matt Hill <9935159+MattDHill@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:52:52 -0700 Subject: [PATCH 13/38] fix(ci): pair a new default line with next/ in multi-line repos (#4807) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit sync-next chose plain `next` for the default branch whenever `next/` did not exist yet. In a repo already carrying `next/*` lines, moving the default to a new line made it try to create `next`, which git refuses beside `next/*` ("directory file conflict") — as bitcoin-core-startos hit when 32.x became its default. Any existing `next/*` branch now means every base pairs with its own `next/`. Co-authored-by: Claude Opus 5.5 --- .github/actions/sync-next/sync-next.mjs | 7 ++++++- .github/actions/tests/sync-next.test.mjs | 7 +++++++ projects/start-sdk/docs/src/project-structure.md | 2 +- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/.github/actions/sync-next/sync-next.mjs b/.github/actions/sync-next/sync-next.mjs index edc5417307..caee018381 100644 --- a/.github/actions/sync-next/sync-next.mjs +++ b/.github/actions/sync-next/sync-next.mjs @@ -32,8 +32,13 @@ export async function syncNext({ cwd, base, forge, botName, botEmail }) { ) const defaultBranch = await forge.defaultBranch() + const lineBranches = git( + 'for-each-ref', + '--format=%(refname)', + 'refs/remotes/origin/next/', + ) const target = - exists(`next/${base}`) || base !== defaultBranch ? `next/${base}` : 'next' + lineBranches || base !== defaultBranch ? `next/${base}` : 'next' const baseSha = git('rev-parse', `origin/${base}`) if (!exists(target)) { git('push', 'origin', `${baseSha}:refs/heads/${target}`) diff --git a/.github/actions/tests/sync-next.test.mjs b/.github/actions/tests/sync-next.test.mjs index 3a4754705a..5732c51814 100644 --- a/.github/actions/tests/sync-next.test.mjs +++ b/.github/actions/tests/sync-next.test.mjs @@ -84,6 +84,13 @@ test('uses explicit next/base even for the default branch', async t => { assert.equal(f.remoteSha('next/master'), tip) }) +test('a default branch with no next/base joins its sibling next/* lines', async t => { + const f = fixture(t) + f.git('push', 'origin', 'master:refs/heads/next/older') + assert.equal(await f.run(), 'created') + assert.equal(f.remoteSha('next/master'), f.initial) +}) + test('non-default branches get their own iteration branch', async t => { const f = fixture(t) f.forge.defaultBranch = async () => 'main' diff --git a/projects/start-sdk/docs/src/project-structure.md b/projects/start-sdk/docs/src/project-structure.md index 37041dcd55..5869bf9a0c 100644 --- a/projects/start-sdk/docs/src/project-structure.md +++ b/projects/start-sdk/docs/src/project-structure.md @@ -240,7 +240,7 @@ jobs: pull-requests: write ``` -The paired branch is derived rather than configured: an explicit `next/` is used where one exists — that is how the multi-branch packages keep one iteration branch per major line or flavor — and otherwise the repo's default branch pairs with a plain `next`. **A repo with no `next` gets one created at the base tip on the first run**, so a package never has to be seeded by hand. +The paired branch is derived rather than configured: a repo with any `next/` branch pairs every base with its own `next/` — that is how the multi-branch packages keep one iteration branch per major line or flavor, including a new line that just became the default branch — and otherwise the repo's default branch pairs with a plain `next`. **A repo with no `next` gets one created at the base tip on the first run**, so a package never has to be seeded by hand. Neither `next` nor the base branch is force-pushed or rewritten. `next` is fast-forwarded when it is merely behind, given a merge commit when it carries unmerged work, and left untouched with a pull request opened for a human only when that merge conflicts. That pull request is headed by a throwaway `sync-next/` branch rather than the base itself, so resolving its conflicts in GitHub's web editor — which commits to the head branch — cannot land on the base. **Merge it with a merge commit rather than a squash**, so `next` comes out with the base as an ancestor; a squash leaves equivalent content under a fresh commit and the following sync conflicts all over again. `workflow_dispatch` is there so a package can be brought into line without waiting for its next merge. From 781fd64ac252a78a9a38a6c1341acc6c085fed73 Mon Sep 17 00:00:00 2001 From: "start9-docs-bot[bot]" <315476469+start9-docs-bot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:26:54 +0000 Subject: [PATCH 14/38] docs: backport live-docs 030153053 to master Backports the following from live-docs: - 030153053 docs(start-sdk): release notes never state the minimum StartOS version (#4808) --- projects/start-sdk/docs/src/versions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/start-sdk/docs/src/versions.md b/projects/start-sdk/docs/src/versions.md index dd57e76ad4..084d4a751f 100644 --- a/projects/start-sdk/docs/src/versions.md +++ b/projects/start-sdk/docs/src/versions.md @@ -212,7 +212,7 @@ When making changes to the StartOS wrapper without upstream changes: `releaseNotes` renders as markdown in the StartOS UI. **Describe what changed in the release.** Read the upstream release notes / changelog for the bumped range, pull out the highlights that matter to a user (notable features, important fixes, security patches, breaking changes / required actions), and summarize them. Then link to the complete upstream release notes or changelog so the user can read the full detail. If the upstream release is genuinely trivial (e.g. a dependency-only patch), say that explicitly. -**Say what a user observes, never how it was done.** Name the difference someone running the service will notice: a feature, a fix described by its symptom, a required action. Leave out the mechanism (the module, flag or config key that changed), the package's internals (an SDK bump, a refactor, a dependency refresh) and the history of a defect ("introduced in 2.37.0", "previously…"); they belong in the commit message and the PR body. A wrapper change nobody can observe gets no line of its own. Every instruction must be one a StartOS user can carry out from the StartOS UI or the service itself — never a host command (`sysctl`, `apt`) and never a pointer to guidance the note doesn't link. +**Say what a user observes, never how it was done.** Name the difference someone running the service will notice: a feature, a fix described by its symptom, a required action. Leave out the mechanism (the module, flag or config key that changed), the package's internals (an SDK bump, a refactor, a dependency refresh) and the history of a defect ("introduced in 2.37.0", "previously…"); they belong in the commit message and the PR body. A wrapper change nobody can observe gets no line of its own. Never state the minimum StartOS version: only a server that already meets it is shown the notes, and StartOS offers the update to no other. Every instruction must be one a StartOS user can carry out from the StartOS UI or the service itself — never a host command (`sysctl`, `apt`) and never a pointer to guidance the note doesn't link. **Release notes are the only home for what an update asks of the user.** A step to take before or after updating, a warning, a credential to rotate, a client to upgrade: each goes here and nowhere else. `instructions.md` and `README.md` describe the service as it is to someone who never ran an older version, so an update adds nothing to them unless it changes that description ([Writing Instructions — What does not belong](./writing-instructions.md#what-does-not-belong-in-instructions)). From 8aef1d8f394fffdc0edc3a578f031366c029a0d0 Mon Sep 17 00:00:00 2001 From: Helix the Red <355572797+helix-red@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:39:38 -0700 Subject: [PATCH 15/38] fix(storage): back up shared volumes with their stored container ids (#4806) * fix(storage): back up shared volumes with their stored container ids Shared-volume backups copied the service view, which carries the global LXC offset (+100000), and restores stripped it again through an unshifting idmapped mount. Backups now copy the source as stored, so they hold container ids like package backups, and restores copy them back directly. Shared volumes are unreleased, so the offset format is not read. `SourceDefinition::unmapped_filesystem` owns the raw policy: the local subvolume, the disk without an idmap, and CIFS without the forced service owner. Backup targets and shared-volume backups both use it; `open_unmapped_source` and `open_source` share one preparation path. A CIFS backup holds the owners the share reports, normally root. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(storage): map shared volumes only when attaching them to a container Shared-volume sources are mounted on the host without an idmap: the local subvolume and the disk as stored, with container ids. Attaching a source into a container stages it through an idmapped detached clone with the base LXC map. CIFS cannot be idmapped, so it keeps its forced service owner at the source and attaches unmapped. With one host view per source, the separate unmapped view goes away: backups copy the host view directly, holding container ids, and restores copy them back. A CIFS view carries only the forced owner, so its backup copy is owned by root instead. Backup targets keep their own raw policy. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(storage): report shared-volume source mapping failures as unavailable Mapping a shared volume when it is attached moved idmap and clone failures past the handler that turns source failures into the optional `unavailable` result, so an external filesystem rejecting MOUNT_ATTR_IDMAP or a userns-helper timeout rejected the RPC instead. mount_source now separates source cloning/idmapping failures from request and target attachment failures; the effect maps the former through one unavailable-result owner and keeps the latter as errors. The placeholder stays installed. Also shares one open_tree_attr idmap syscall between the path and pinned descriptor forms, and corrects the architecture note that claimed source filesystem types perform idmapping. Adapted from the cross-review proposal. Co-Authored-By: helix-white <267227783+helix-a@users.noreply.github.com> Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --------- Co-authored-by: helix-white <267227783+helix-a@users.noreply.github.com> --- shared-libs/crates/start-core/ARCHITECTURE.md | 6 +- .../crates/start-core/src/backup/volume.rs | 118 ++++++++++++------ .../src/disk/mount/filesystem/syscall.rs | 31 +++-- .../src/disk/mount/filesystem/syscall_stub.rs | 4 + .../src/service/effects/shared_volumes.rs | 63 ++++++++-- .../start-core/src/shared_volumes/mounts.rs | 72 +++++++++-- .../src/shared_volumes/mounts/tests.rs | 16 +-- .../start-core/src/shared_volumes/source.rs | 25 ++-- .../src/shared_volumes/source/ownership.rs | 2 +- .../src/shared_volumes/source/tests.rs | 98 ++++++++++----- 10 files changed, 323 insertions(+), 112 deletions(-) diff --git a/shared-libs/crates/start-core/ARCHITECTURE.md b/shared-libs/crates/start-core/ARCHITECTURE.md index 5e9a64bbb8..5af1d91ab9 100644 --- a/shared-libs/crates/start-core/ARCHITECTURE.md +++ b/shared-libs/crates/start-core/ARCHITECTURE.md @@ -35,7 +35,7 @@ how `startbox` dispatches to `startd`, `start-cli`, etc. The per-entrypoint logi - `src/net/` — Networking (DNS, ACME, WiFi, Tor, WireGuard, gateway/NAT) - `src/net/static_server.rs` — UI and authenticated archive/icon resources. Resource signatures reuse `SignatureAuthorizationContext::check_pubkey` for enrollment. The registry-icon proxy signs exact content-addressed icon URLs under saved registries with the server identity key, using the shared icon path validator and canonical registry enumeration. Signed upstream GETs refuse redirects; other images and archive download hosts retain their existing transport policy. Upstream status, content type and cache policy pass through; unrelated response headers do not. - `src/s9pk/` — S9PK package format (merkle archive) -- `src/lxc/` — LXC container management for packages. `filesystem::service_filesystem` owns base UID/GID mapping and package-remap composition for package volumes, shared local/disk volumes, runtime rootfs, assets, images and backup views. CIFS supplies service ownership through mount options; host-only staging and backup targets retain raw filesystem views. +- `src/lxc/` — LXC container management for packages. `filesystem::service_filesystem` owns base UID/GID mapping and package-remap composition for package volumes, runtime rootfs, assets, images and backup views. Shared local and disk volumes are mounted on the host without an idmap; attaching one into a container applies the base map. CIFS supplies service ownership through mount options; host-only staging and backup targets retain raw filesystem views. - `src/install/`, `src/update/` — Package install and OS/package update flows - `src/trusted_keys.rs` — Individual signing-key trust (`TrustedKey.publicKey`), immutable import provenance, committed initial certificates in `src/trusted_keys/initial/`, and legacy OS-signer adapters. `src/trusted_keys/legacy.rs` owns historical grouped-keyring decoding and migration to canonical per-key records; downgrade restores the historical array shape. `src/trusted_keys/connection.rs` atomically records registry connections and advertised-key snapshots. Connecting trusts keys new to the server for packages. Registry index synchronization imports newly listed keys disabled, preserves existing trust and provenance, and issues a `RegistryKeyAdded` notification for each key new to the server and a `RegistryKeyDropped` notification for each key the registry stops offering. Selecting the StartOS update registry trusts its listed keys for OS updates, and that registry cannot be removed. Connected registry listings determine deletion protection, and the last OS-update key cannot lose its trust. `src/sign/gpg.rs` retains original exports and attributes self-certified identities and OpenPGP fingerprints to each signing key. - `src/update/signer_files.rs` — Mirrors OS-update trust to PEM files in the config overlay at `/etc/startos/os-signers`, reconciled from the database during RPC initialization after database migrations. Trust-changing RPCs serialize database mutations and await filesystem persistence. Diagnostic updates read that selection without the data drive, falling back to the image's three production keys only before a selection has been saved. Regular `LocalAuth` verifies its protected cookie, strips caller-supplied `__Auth_local` claims, and injects its authentication result when `get_local_auth` metadata requests it. The diagnostic update endpoint uses that injected result to authorize trust overrides. @@ -135,7 +135,7 @@ See [patchdb.md](patchdb.md) for `TypedDbWatch` construction, API, and usage ## Shared service volumes -`shared_volumes::mounts` stages confined sources beneath the host-owned `/media/startos/shared-volumes` service path, separate from the package-volume ID namespace. One `mount-shared-volume` request owns authorization, placeholder installation and data attachment. The host pins source and target directories, clones in the service mount namespace, and retains the descriptor returned by attachment. Staging paths and lifecycle remain internal; there is no SDK preparation token or second attachment request. `DetachedMount::configure_bind` owns bind policy for this operation and ordinary `start-container bind-mount`: writable trees retain incoming source propagation; read-only trees are private and recursively read-only. Propagation is set before attachment, preserving cleanup of copies in execution namespaces. Each target keeps an inaccessible read-only placeholder below optional data mounts. Read-only staging crosses into the service user namespace before target binding; the service cannot clear the inherited read-only lock. Retiring a stage leaves independently cloned bindings and open handles usable. +`shared_volumes::mounts` stages confined sources beneath the host-owned `/media/startos/shared-volumes` service path, separate from the package-volume ID namespace. One `mount-shared-volume` request owns authorization, placeholder installation and data attachment. The host pins source and target directories, clones in the service mount namespace, and retains the descriptor returned by attachment. Staging paths and lifecycle remain internal; there is no SDK preparation token or second attachment request. `DetachedMount::configure_bind` owns bind policy for this operation and ordinary `start-container bind-mount`: writable trees retain incoming source propagation; read-only trees are private and recursively read-only. Propagation is set before attachment, preserving cleanup of copies in execution namespaces. Each target keeps an inaccessible read-only placeholder below optional data mounts. Read-only staging crosses into the service user namespace before target binding; the service cannot clear the inherited read-only lock. Retiring a stage leaves independently cloned bindings and open handles usable. Source cloning and idmapping failures return optional unavailability; request validation and target attachment failures remain RPC errors. `shared_volumes::access` weakly registers each live staging table, including tables awaiting asynchronous service cleanup. A mount request re-authorizes after source preparation and holds the management gate through placeholder installation, attachment and registration. Grant changes and removal hold it exclusively while persisting authorization and detaching incompatible SDK-managed targets and stages. This covers manually managed subcontainers without a reactive subscription. The request owns its operation across caller cancellation. Independent aliases and open handles remain outside this best-effort boundary. Persisted grants govern future preparation rather than proving all earlier access has ended. SDK reactive consumers reconcile through their ordinary workload lifecycle. Removing a volume retires its managed stages across services before deleting local data; cleanup failures leave local registration available for retry. @@ -143,7 +143,7 @@ See [patchdb.md](patchdb.md) for `TypedDbWatch` construction, API, and usage `Public.backupTargets` owns registered local-folder, external-folder and CIFS destinations. Runtime backup/restore/conversion methods resolve these IDs; setup retains its inline recovery-source contract. Attached drives register through source creation or explicit `backup.target.find`. Find reuses disk discovery and shared source preparation to register partition roots with recognized `StartOSBackupsV2` metadata, without recursive folder discovery or modifying backup contents. Background inventory scans never register targets. The catalog atomically skips already registered filesystem-UUID/root pairs, retaining names and settings; a removed target can be rediscovered with a fresh identity. Boot consumes the historical private CIFS catalog into targets and password-only private credentials, preserving existing CIFS IDs. New IDs are GUIDs independent of connection details. Managed local shared volumes and targets are Btrfs subvolumes beneath the persistent `PACKAGE_DATA` partition at `shared-volumes/` and `backup-targets/`. `DATA_DIR` itself is a volatile mount scaffold. Their path owners also supply generated `managedStorage` directories for clients; the UI presents names rather than opaque catalog IDs or internal managed paths. Migration consumes the legacy private CIFS catalog; rollback to an older same-version development build without registered-target support is unsupported. -`backup::target::catalog` reuses shared source preparation and inspection DTOs. `PreparedFilesystem` shares managed-subvolume validation and filesystem delegation; concrete filesystem types preserve idmapped/shared-CIFS service policy and raw backup policy. `PinnedDirectory` owns confined descriptor opening and its stable path. Prepared callers retain their backing mount; observer reads retain the directory descriptor without mount-cache ownership. Managed local removal reserves the existing mount-cache slot, rejects active users and excludes new mounts through committed subvolume deletion, including nested subvolume roots. Shared-volume removal revokes future authorization and retires managed staging sources before deleting local data. Registration survives failed or interrupted deletion for retry; successful deletion unregisters the source. The Btrfs cleaner reclaims the removed subvolume's space asynchronously. Boot converts ordinary local roots with the package-volume reflink/swap recovery owner before observers or services start. Local shared roots carrying the legacy LXC ownership offset are replaced through the inverse ownership view and the same recoverable reflink/swap owner, independently of version-keyed migrations; backup targets retain raw owners. Obsolete pending local deletions recover as named, ungranted registrations during database normalization. External removal preserves contents. Observations reject stale source/credential snapshots and never recreate removed records. Backup, conversion and legacy-cleanup completion refresh target recovery metadata. Legacy CIFS add/update validate the share and existing unencrypted backup metadata before publishing a change; the target lifecycle RPCs retain unavailable configuration intent. Both reuse the target-content inspection owner, where capacity failures are diagnostic rather than a mount or metadata-validation failure. Mounted targets use the same metadata reader for initialization and recovery without opening another mount. The catalog requires validated contents before an unknown or unavailable target becomes available; folder-only status updates cannot clear metadata errors. The backup terminal-report owner persists completed background runs in private history with the target name captured at acceptance; `backup.history.list` pages them newest first. Synchronous request/setup rejection does not create a completed background run. +`backup::target::catalog` reuses shared source preparation and inspection DTOs. `PreparedFilesystem` shares managed-subvolume validation and filesystem delegation; concrete filesystem types preserve shared-CIFS service ownership and raw host storage policy. Shared-volume backups copy that single host view, holding container ids like package backups; a CIFS backup, whose view carries only the forced service owner, is owned by root. Restores copy them back unchanged. `PinnedDirectory` owns confined descriptor opening and its stable path. Prepared callers retain their backing mount; observer reads retain the directory descriptor without mount-cache ownership. Managed local removal reserves the existing mount-cache slot, rejects active users and excludes new mounts through committed subvolume deletion, including nested subvolume roots. Shared-volume removal revokes future authorization and retires managed staging sources before deleting local data. Registration survives failed or interrupted deletion for retry; successful deletion unregisters the source. The Btrfs cleaner reclaims the removed subvolume's space asynchronously. Boot converts ordinary local roots with the package-volume reflink/swap recovery owner before observers or services start. Local shared roots carrying the legacy LXC ownership offset are replaced through the inverse ownership view and the same recoverable reflink/swap owner, independently of version-keyed migrations; backup targets retain raw owners. Obsolete pending local deletions recover as named, ungranted registrations during database normalization. External removal preserves contents. Observations reject stale source/credential snapshots and never recreate removed records. Backup, conversion and legacy-cleanup completion refresh target recovery metadata. Legacy CIFS add/update validate the share and existing unencrypted backup metadata before publishing a change; the target lifecycle RPCs retain unavailable configuration intent. Both reuse the target-content inspection owner, where capacity failures are diagnostic rather than a mount or metadata-validation failure. Mounted targets use the same metadata reader for initialization and recovery without opening another mount. The catalog requires validated contents before an unknown or unavailable target becomes available; folder-only status updates cannot clear metadata errors. The backup terminal-report owner persists completed background runs in private history with the target name captured at acceptance; `backup.history.list` pages them newest first. Synchronous request/setup rejection does not create a completed background run. Backup-FS mount caching and trash sweeps use actual directory identity, including through pinned descriptors and aliases; a replacement at the same pathname does not reuse an old encrypted mount. Public source errors redact private cache identities. diff --git a/shared-libs/crates/start-core/src/backup/volume.rs b/shared-libs/crates/start-core/src/backup/volume.rs index cf2322a6cc..03d4b8a90d 100644 --- a/shared-libs/crates/start-core/src/backup/volume.rs +++ b/shared-libs/crates/start-core/src/backup/volume.rs @@ -13,10 +13,9 @@ use super::target::{BackupTargetId, BackupTargetSource, SharedVolumeBackupInfo, use super::{PackageBackupReport, VolumeBackupReport}; use crate::context::{CliContext, RpcContext}; use crate::disk::mount::backup::BackupMountGuard; -use crate::disk::mount::filesystem::bind::Bind; use crate::disk::mount::filesystem::block_dev::BlockDev; use crate::disk::mount::filesystem::{FileSystem, ReadOnly, ReadWrite}; -use crate::disk::mount::guard::{GenericMountGuard, TmpMountGuard}; +use crate::disk::mount::guard::GenericMountGuard; use crate::disk::mount::util::sync_directory; use crate::prelude::*; use crate::rpc_continuations::Guid; @@ -42,13 +41,26 @@ pub(super) fn selected_ids( ) } -/// Preserves symlinks, hard links, permissions, numeric owners, times, ACLs and xattrs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Owners { + /// Numeric owners as the source holds them. + Keep, + /// Root, the container root, for a view whose owners are forced rather than stored. + Root, +} + +/// Preserves symlinks, hard links, permissions, times, ACLs and xattrs, and owners as requested. /// CIFS metadata fidelity is limited by what the mounted source exposes. -async fn copy_folder(source: &Path, destination: &Path) -> Result<(), Error> { +async fn copy_folder(source: &Path, destination: &Path, owners: Owners) -> Result<(), Error> { let mut contents = source.as_os_str().to_os_string(); contents.push("/"); Command::new("rsync") - .args(["-aHAXS", "--numeric-ids", "--timeout=300", "--"]) + .args(["-aHAXS", "--numeric-ids", "--timeout=300"]) + .args(match owners { + Owners::Keep => &[][..], + Owners::Root => &["--no-owner", "--no-group"][..], + }) + .arg("--") .arg(contents) .arg(destination) .timeout(Some(Duration::from_secs(24 * 60 * 60))) @@ -57,12 +69,12 @@ async fn copy_folder(source: &Path, destination: &Path) -> Result<(), Error> { Ok(()) } -async fn stage_copy(data: &Path, source: &Path) -> Result { +async fn stage_copy(data: &Path, source: &Path, owners: Owners) -> Result { let generation = Guid::new().to_string(); let staging = data.join(format!(".{generation}.staging")); tokio::fs::create_dir_all(&staging).await?; let result = async { - copy_folder(source, &staging).await?; + copy_folder(source, &staging, owners).await?; sync_directory(&staging).await?; tokio::fs::rename(&staging, data.join(&generation)).await?; sync_directory(data).await?; @@ -106,7 +118,7 @@ pub(super) async fn measure_backup( ) } -/// Copies the service view of the volume, retaining host-visible owners. +/// Copies the host view: container ids, as package backups hold. A CIFS copy is owned by root. pub(super) async fn backup_volume( ctx: &RpcContext, backup: &BackupMountGuard, @@ -139,7 +151,12 @@ pub(super) async fn backup_volume( if crate::util::io::directories_overlap(source.path(), &target_data).await? { return Err(overlapping_target_error()); } - stage_copy(&backup.shared_volume_data(id), source.path()).await + let owners = if source.stores_container_ids() { + Owners::Keep + } else { + Owners::Root + }; + stage_copy(&backup.shared_volume_data(id), source.path(), owners).await } .await; source.unmount().await?; @@ -330,16 +347,7 @@ async fn restore_local_copy>>( let mut incomplete = IncompleteRestore(Some(path.clone())); let result = async { source::set_local_permissions(&path).await?; - // Volume backups retain host-visible owners, including the LXC offset. - let unshifted = TmpMountGuard::mount( - &crate::lxc::unshifted_filesystem(Bind::new(source)), - ReadOnly, - ) - .await - .with_kind(ErrorKind::Backup)?; - let copied = copy_folder(unshifted.path(), &path).await; - unshifted.unmount().await?; - copied?; + copy_folder(source, &path, Owners::Keep).await?; source::set_local_permissions(&path).await?; sync_directory(&path).await?; // Publication can commit after its caller cancels. @@ -554,7 +562,7 @@ mod tests { .unwrap(); std::fs::hard_link(&file, source.join("hard-link")).unwrap(); symlink("nested/.contents", source.join("symbolic-link")).unwrap(); - let generation = stage_copy(&data, &source).await.unwrap(); + let generation = stage_copy(&data, &source, Owners::Keep).await.unwrap(); let destination = generation_path(&data, &info(generation)).unwrap(); let copied = destination.join("nested/.contents"); assert_eq!(std::fs::read(&copied).unwrap(), b"complete folder contents"); @@ -583,10 +591,10 @@ mod tests { let data = fixture.path().join("archive/data"); std::fs::create_dir(&source).unwrap(); std::fs::write(source.join("sentinel"), b"old successful backup").unwrap(); - let original = info(stage_copy(&data, &source).await.unwrap()); + let original = info(stage_copy(&data, &source, Owners::Keep).await.unwrap()); let original_file = generation_path(&data, &original).unwrap().join("sentinel"); assert!( - stage_copy(&data, &fixture.path().join("missing-source")) + stage_copy(&data, &fixture.path().join("missing-source"), Owners::Keep) .await .is_err() ); @@ -595,7 +603,7 @@ mod tests { b"old successful backup" ); std::fs::write(source.join("sentinel"), b"replacement not published").unwrap(); - let unpublished = info(stage_copy(&data, &source).await.unwrap()); + let unpublished = info(stage_copy(&data, &source, Owners::Keep).await.unwrap()); assert_eq!( std::fs::read(&original_file).unwrap(), b"old successful backup" @@ -605,6 +613,56 @@ mod tests { assert!(!generation_path(&data, &unpublished).unwrap().exists()); } + fn container_owned_source(root: &Path) -> Option { + let source = root.join("source"); + std::fs::create_dir(&source).unwrap(); + std::fs::write(source.join("sentinel"), b"container data").unwrap(); + std::os::unix::fs::chown(source.join("sentinel"), Some(1000), Some(2000)).ok()?; + Some(source) + } + + #[tokio::test] + async fn a_backup_copy_keeps_container_ids() { + let root = tempfile::tempdir().unwrap(); + let Some(source) = container_owned_source(root.path()) else { + eprintln!("skipped: needs permission to chown to container ids"); + return; + }; + let data = root.path().join("data"); + let generation = stage_copy(&data, &source, Owners::Keep).await.unwrap(); + let metadata = std::fs::metadata(data.join(generation).join("sentinel")).unwrap(); + assert_eq!((metadata.uid(), metadata.gid()), (1000, 2000)); + let generation = stage_copy(&data, &source, Owners::Root).await.unwrap(); + let metadata = std::fs::metadata(data.join(generation).join("sentinel")).unwrap(); + assert_eq!( + (metadata.uid(), metadata.gid()), + ( + nix::unistd::geteuid().as_raw(), + nix::unistd::getegid().as_raw() + ) + ); + } + + #[tokio::test] + #[ignore = "requires root, BTRFS_TEST_VOLUMES_DIR and a private Linux mount namespace"] + async fn backup_and_restore_round_trip_preserves_container_ids() { + let fixture = crate::util::btrfs::tests::directory(); + let source = container_owned_source(fixture.path()).unwrap(); + let data = fixture.path().join("data"); + let generation = stage_copy(&data, &source, Owners::Keep).await.unwrap(); + let created = restore_local_copy( + fixture.path(), + &data.join(generation), + "Photos".into(), + |_, _| async { Ok(()) }, + ) + .await + .unwrap(); + let metadata = + std::fs::metadata(local_path(fixture.path(), &created).join("sentinel")).unwrap(); + assert_eq!((metadata.uid(), metadata.gid()), (1000, 2000)); + } + #[tokio::test] #[ignore = "requires root, BTRFS_TEST_VOLUMES_DIR and a private Linux mount namespace"] async fn restore_creates_a_new_local_volume_without_touching_existing_data() { @@ -616,8 +674,7 @@ mod tests { std::fs::create_dir(&source).unwrap(); std::fs::write(old_path.join("sentinel"), b"existing data").unwrap(); std::fs::write(source.join("sentinel"), b"restored data").unwrap(); - std::os::unix::fs::chown(&source, Some(100000), Some(100000)).unwrap(); - std::os::unix::fs::chown(source.join("sentinel"), Some(101000), Some(102000)).unwrap(); + std::os::unix::fs::chown(source.join("sentinel"), Some(1000), Some(2000)).unwrap(); let created = restore_local_copy(fixture.path(), &source, "Photos".into(), |id, volume| { assert_ne!(id, old_id); assert_eq!(volume.name, "Photos"); @@ -648,15 +705,6 @@ mod tests { let restored = local_path(fixture.path(), &created).join("sentinel"); let metadata = std::fs::metadata(&restored).unwrap(); assert_eq!((metadata.uid(), metadata.gid()), (1000, 2000)); - let view = TmpMountGuard::mount( - &source::SourceFilesystem::local(local_path(fixture.path(), &created)), - ReadOnly, - ) - .await - .unwrap(); - let metadata = std::fs::metadata(view.path().join("sentinel")).unwrap(); - assert_eq!((metadata.uid(), metadata.gid()), (101000, 102000)); - view.unmount().await.unwrap(); } #[tokio::test] @@ -666,8 +714,6 @@ mod tests { let source = fixture.path().join("backup"); std::fs::create_dir(&source).unwrap(); std::fs::write(source.join("sentinel"), b"backup data").unwrap(); - std::os::unix::fs::chown(&source, Some(100000), Some(100000)).unwrap(); - std::os::unix::fs::chown(source.join("sentinel"), Some(100000), Some(100000)).unwrap(); let failed_copy = restore_local_copy( fixture.path(), &fixture.path().join("missing"), diff --git a/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall.rs b/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall.rs index 391e0a3c68..0f1ae93e26 100644 --- a/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall.rs +++ b/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall.rs @@ -1,7 +1,7 @@ //! Detached Linux bind mounts with optional idmaps and read-only attributes. //! `open_tree_attr` requires Linux 6.15+ for cloning an already-idmapped source. -use std::ffi::{CString, OsString}; +use std::ffi::{CStr, CString, OsString}; use std::io; use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd, RawFd}; use std::os::unix::ffi::OsStrExt; @@ -103,25 +103,42 @@ pub fn open_tree_attr_idmap( recursive: bool, userns: BorrowedFd, ) -> Result { - let p = cstr_path(path)?; - let flags = clone_flags(recursive); + open_tree_attr_idmap_at(AT_FDCWD, &cstr_path(path)?, clone_flags(recursive), userns) +} + +/// Clones a pinned directory without its child mounts, idmapped through the user namespace. +pub fn open_tree_attr_idmap_fd(source: BorrowedFd, userns: BorrowedFd) -> Result { + open_tree_attr_idmap_at( + source.as_raw_fd(), + &cstr_str("")?, + clone_flags(false) | AT_EMPTY_PATH as libc::c_uint, + userns, + ) +} + +fn open_tree_attr_idmap_at( + source: RawFd, + path: &CStr, + flags: libc::c_uint, + userns: BorrowedFd, +) -> Result { let attr = MountAttr { attr_set: MOUNT_ATTR_IDMAP, attr_clr: 0, propagation: 0, userns_fd: userns.as_raw_fd() as u64, }; - let r = unsafe { + let raw = unsafe { libc::syscall( SYS_OPEN_TREE_ATTR, - AT_FDCWD, - p.as_ptr(), + source, + path.as_ptr(), flags, &attr as *const _ as *const libc::c_void, std::mem::size_of::(), ) }; - fd_from_raw(r, "open_tree_attr IDMAP") + fd_from_raw(raw, "open_tree_attr IDMAP") } /// A detached clone rooted at a pinned directory, optionally including submounts. diff --git a/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall_stub.rs b/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall_stub.rs index 3603628b7d..914c948d71 100644 --- a/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall_stub.rs +++ b/shared-libs/crates/start-core/src/disk/mount/filesystem/syscall_stub.rs @@ -52,6 +52,10 @@ pub fn open_tree_clone_fd(_source: BorrowedFd, _recursive: bool) -> Result Result { + unsupported() +} + pub fn open_tree_attr_idmap( _path: &Path, _recursive: bool, diff --git a/shared-libs/crates/start-core/src/service/effects/shared_volumes.rs b/shared-libs/crates/start-core/src/service/effects/shared_volumes.rs index 5dcf44f587..baab4647f5 100644 --- a/shared-libs/crates/start-core/src/service/effects/shared_volumes.rs +++ b/shared-libs/crates/start-core/src/service/effects/shared_volumes.rs @@ -6,6 +6,7 @@ use crate::prelude::*; use crate::service::effects::callbacks::CallbackHandler; use crate::service::effects::prelude::*; use crate::service::rpc::CallbackId; +use crate::shared_volumes::mounts::MountSourceError; use crate::shared_volumes::source::SourceDefinition; use crate::shared_volumes::{SharedVolume, SharedVolumeAvailability, SharedVolumeId}; @@ -190,6 +191,20 @@ async fn authorize_mount( ) } +/// Source preparation reports unavailability; request and attachment failures reject. +fn mount_failure(error: MountSourceError) -> Result { + match error { + MountSourceError::Source(error) => Ok(SharedVolumeMountResult::Unavailable { + reason: if matches!(error.kind, ErrorKind::Timeout) { + SharedVolumeUnavailableReason::Timeout + } else { + SharedVolumeUnavailableReason::SourceUnavailable + }, + }), + MountSourceError::Attachment(error) => Err(error), + } +} + /// Owns authorization, placeholder installation and data attachment through cancellation. pub async fn mount_shared_volume( context: EffectContext, @@ -268,15 +283,7 @@ async fn mount_shared_volume_owned( .await?; let source = match source { Ok(prepared) => prepared?, - Err(error) => { - return Ok(SharedVolumeMountResult::Unavailable { - reason: if matches!(error.kind, ErrorKind::Timeout) { - SharedVolumeUnavailableReason::Timeout - } else { - SharedVolumeUnavailableReason::SourceUnavailable - }, - }); - } + Err(error) => return mount_failure(MountSourceError::Source(error)), }; mounts .mount_source( @@ -287,8 +294,9 @@ async fn mount_shared_volume_owned( readonly, &service_root, ) - .await?; - Ok(SharedVolumeMountResult::Mounted) + .await + .map(|()| SharedVolumeMountResult::Mounted) + .or_else(mount_failure) } #[cfg(test)] @@ -298,6 +306,39 @@ mod tests { SharedVolumeCredentials, SharedVolumeDrive, SharedVolumeGrant, SharedVolumeSource, }; + #[test] + fn source_preparation_failures_return_optional_unavailability() { + for (kind, reason) in [ + (ErrorKind::Filesystem, "sourceUnavailable"), + (ErrorKind::Timeout, "timeout"), + ] { + let outcome = mount_failure(MountSourceError::Source(Error::new( + eyre!("source preparation failed"), + kind, + ))) + .unwrap(); + assert_eq!( + serde_json::to_value(outcome).unwrap(), + serde_json::json!({"kind": "unavailable", "reason": reason}) + ); + } + } + + #[test] + fn attachment_failures_keep_their_error_even_for_source_like_kinds() { + for kind in [ + ErrorKind::Authorization, + ErrorKind::InvalidRequest, + ErrorKind::Filesystem, + ErrorKind::Timeout, + ] { + let error = + mount_failure(Error::new(eyre!("attachment failed"), kind).into()).unwrap_err(); + assert_eq!(error.kind, kind); + assert!(error.to_string().contains("attachment failed")); + } + } + #[test] fn consumers_are_notified_only_when_their_mount_inputs_change() { let package: PackageId = "consumer".parse().unwrap(); diff --git a/shared-libs/crates/start-core/src/shared_volumes/mounts.rs b/shared-libs/crates/start-core/src/shared_volumes/mounts.rs index f84f4bf513..7f275f2796 100644 --- a/shared-libs/crates/start-core/src/shared_volumes/mounts.rs +++ b/shared-libs/crates/start-core/src/shared_volumes/mounts.rs @@ -5,7 +5,8 @@ use std::path::{Component, Path, PathBuf}; use std::sync::Arc; use crate::disk::mount::filesystem::syscall::{ - DetachedMount, MountNamespace, open_beneath, open_tree_clone_fd, same_mount, unmount_fd, + DetachedMount, MountNamespace, open_beneath, open_tree_attr_idmap_fd, open_tree_clone_fd, + same_mount, unmount_fd, userns_fd_from_idmap, }; use crate::disk::mount::guard::{GenericMountGuard, TmpMountGuard}; use crate::prelude::*; @@ -27,7 +28,20 @@ impl AttachedMount { readonly: bool, namespace: Arc, ) -> Result { - let detached = DetachedMount::from_fd(open_tree_clone_fd(source.as_fd(), false)?); + Self::attach( + DetachedMount::from_fd(open_tree_clone_fd(source.as_fd(), false)?), + destination, + readonly, + namespace, + ) + } + + fn attach( + detached: DetachedMount, + destination: &OwnedFd, + readonly: bool, + namespace: Arc, + ) -> Result { detached.set_private()?; detached.set_readonly(readonly)?; let mount = namespace.run(|| detached.attach_to_fd(destination.as_fd()))?; @@ -93,6 +107,8 @@ impl AsFd for PinnedDirectory { pub struct PreparedSource { directory: PinnedDirectory, guard: TmpMountGuard, + /// The host view holds container ids; attaching applies the container's map. + container_ids: bool, } impl PreparedSource { @@ -100,11 +116,34 @@ impl PreparedSource { &self.guard } + pub(crate) fn storing_container_ids(mut self) -> Self { + self.container_ids = true; + self + } + + pub(crate) fn stores_container_ids(&self) -> bool { + self.container_ids + } + + async fn clone_for_attachment(&self) -> Result { + let mount = if self.container_ids { + let userns = userns_fd_from_idmap(&[crate::lxc::BASE_IDMAP]).await?; + open_tree_attr_idmap_fd(self.directory.as_fd(), userns.as_fd())? + } else { + open_tree_clone_fd(self.directory.as_fd(), false)? + }; + Ok(DetachedMount::from_fd(mount)) + } + pub async fn open(guard: TmpMountGuard, subpath: Option) -> Result { tokio::task::spawn_blocking(move || { let directory = PinnedDirectory::open(guard.path(), subpath.as_deref().unwrap_or(Path::new("")))?; - Ok(Self { directory, guard }) + Ok(Self { + directory, + guard, + container_ids: false, + }) }) .await .with_kind(ErrorKind::Unknown)? @@ -119,6 +158,7 @@ impl PreparedSource { Ok(Self { directory, guard: self.guard, + container_ids: self.container_ids, }) }) .await @@ -173,6 +213,18 @@ impl StagedMount { } } +#[derive(Debug)] +pub(crate) enum MountSourceError { + Source(Error), + Attachment(Error), +} + +impl From for MountSourceError { + fn from(error: Error) -> Self { + Self::Attachment(error) + } +} + /// Revocation detaches SDK-managed targets and stages, including manually managed subcontainers. /// Independent aliases and open handles remain outside this best-effort boundary. #[derive(Default)] @@ -281,7 +333,7 @@ impl SharedVolumeMounts { source: PreparedSource, readonly: bool, service_root: &Path, - ) -> Result<(), Error> { + ) -> Result<(), MountSourceError> { self.check_allowed()?; let root = self .root @@ -289,12 +341,18 @@ impl SharedVolumeMounts { .or_not_found("shared-volume staging root")?; let key = (guid.clone(), confined_relative(location)?); let slot = self.slots.get_mut(&key).or_not_found("volume mountpoint")?; + let detached = source + .clone_for_attachment() + .await + .map_err(MountSourceError::Source)?; let relative = Path::new(id.as_ref()).join(Guid::new().to_string()); let path = root.directory.path().join(&relative); - tokio::fs::create_dir_all(&path).await?; + tokio::fs::create_dir_all(&path) + .await + .with_kind(ErrorKind::Filesystem)?; let destination = open_beneath(root.directory.path(), &relative)?; - let mount = AttachedMount::bind( - &source.directory, + let mount = AttachedMount::attach( + detached, &destination, readonly, root._mount.namespace.clone(), diff --git a/shared-libs/crates/start-core/src/shared_volumes/mounts/tests.rs b/shared-libs/crates/start-core/src/shared_volumes/mounts/tests.rs index 183e99d225..ed8761c065 100644 --- a/shared-libs/crates/start-core/src/shared_volumes/mounts/tests.rs +++ b/shared-libs/crates/start-core/src/shared_volumes/mounts/tests.rs @@ -131,7 +131,10 @@ async fn mount_managed( guid, Path::new(location), id, - PreparedSource::open(source.clone(), None).await.unwrap(), + PreparedSource::open(source.clone(), None) + .await + .unwrap() + .storing_container_ids(), readonly, &root, ) @@ -146,7 +149,7 @@ async fn real_lxc_best_effort_revocation_preserves_aliases_and_locks_readonly_st use crate::disk::mount::filesystem::ReadWrite; use crate::disk::mount::filesystem::bind::{Bind, FileType}; use crate::disk::mount::guard::MountGuard; - use crate::lxc::{LxcConfig, LxcManager, service_filesystem}; + use crate::lxc::{LxcConfig, LxcManager}; let fixture = crate::util::btrfs::tests::directory(); std::fs::write(fixture.path().join("sentinel"), b"private data").unwrap(); @@ -155,12 +158,9 @@ async fn real_lxc_best_effort_revocation_preserves_aliases_and_locks_readonly_st std::fs::Permissions::from_mode(0o600), ) .unwrap(); - let source = TmpMountGuard::mount( - &service_filesystem(Bind::new(fixture.path()), &[]), - ReadWrite, - ) - .await - .unwrap(); + let source = TmpMountGuard::mount(&Bind::new(fixture.path()), ReadWrite) + .await + .unwrap(); let manager = Arc::new(LxcManager::new()); let first = manager.create(None, LxcConfig::default()).await.unwrap(); let second = manager.create(None, LxcConfig::default()).await.unwrap(); diff --git a/shared-libs/crates/start-core/src/shared_volumes/source.rs b/shared-libs/crates/start-core/src/shared_volumes/source.rs index b3f4bb60f6..4a5f88e275 100644 --- a/shared-libs/crates/start-core/src/shared_volumes/source.rs +++ b/shared-libs/crates/start-core/src/shared_volumes/source.rs @@ -5,7 +5,6 @@ use crate::context::RpcContext; use crate::disk::mount::filesystem::bind::Bind; use crate::disk::mount::filesystem::block_dev::BlockDev; use crate::disk::mount::filesystem::cifs::{Cifs, SharedCifs}; -use crate::disk::mount::filesystem::idmapped::IdMapped; use crate::disk::mount::filesystem::syscall::open_beneath; use crate::disk::mount::filesystem::{FileSystem, MountType, ReadOnly, ReadWrite}; use crate::disk::mount::guard::{GenericMountGuard, TmpMountGuard, WeakMountGuard}; @@ -114,6 +113,11 @@ impl SourceDefinition { } } + /// Whether the host view holds container ids, which attachment maps into a container. + pub(crate) fn stores_container_ids(&self) -> bool { + !matches!(self.source, SharedVolumeSource::Cifs { .. }) + } + pub(super) fn filesystem(&self, id: &SharedVolumeId) -> SourceFilesystem { match &self.source { SharedVolumeSource::Local => { @@ -154,19 +158,17 @@ pub(crate) enum PreparedFilesystem { Disk(D), Cifs(C), } +/// Host views carry no idmap: local and disk files keep container ids, which attachment maps. +/// CIFS cannot be idmapped and presents its forced service owner instead. pub(crate) type SourceFilesystem = - PreparedFilesystem, IdMapped>, SharedCifs>; + PreparedFilesystem, SharedCifs>; impl SourceFilesystem { - // Local files retain unshifted owners on disk; service views apply BASE_IDMAP. pub(crate) fn local(path: PathBuf) -> Self { - Self::Local(crate::lxc::service_filesystem(LocalSubvolume(path), &[])) + Self::Local(LocalSubvolume(path)) } fn external(device: &Path) -> Self { - Self::Disk(crate::lxc::service_filesystem( - BlockDev::new(device.to_owned()), - &[], - )) + Self::Disk(BlockDev::new(device.to_owned())) } } impl FileSystem for PreparedFilesystem { @@ -227,7 +229,12 @@ pub async fn open_source( let result = source_result( async { let mount = TmpMountGuard::mount(&filesystem, mount_type).await?; - prepared = Some(PreparedSource::open(mount, subpath).await?); + let source = PreparedSource::open(mount, subpath).await?; + prepared = Some(if definition.stores_container_ids() { + source.storing_container_ids() + } else { + source + }); Ok(()) } .await, diff --git a/shared-libs/crates/start-core/src/shared_volumes/source/ownership.rs b/shared-libs/crates/start-core/src/shared_volumes/source/ownership.rs index ef99ee3842..c2538093d5 100644 --- a/shared-libs/crates/start-core/src/shared_volumes/source/ownership.rs +++ b/shared-libs/crates/start-core/src/shared_volumes/source/ownership.rs @@ -171,7 +171,7 @@ mod tests { .await .unwrap(); let visible = std::fs::metadata(view.path().join("sentinel")).unwrap(); - assert_eq!((visible.uid(), visible.gid()), (101000, 102000)); + assert_eq!((visible.uid(), visible.gid()), (1000, 2000)); view.unmount().await.unwrap(); let retired = fixture.path().join("volume.convert-old"); legacy(&retired).await; diff --git a/shared-libs/crates/start-core/src/shared_volumes/source/tests.rs b/shared-libs/crates/start-core/src/shared_volumes/source/tests.rs index 726d9cf010..a9ae439224 100644 --- a/shared-libs/crates/start-core/src/shared_volumes/source/tests.rs +++ b/shared-libs/crates/start-core/src/shared_volumes/source/tests.rs @@ -1,23 +1,52 @@ use super::*; #[tokio::test] -async fn local_sources_apply_the_base_map_and_keep_raw_backup_targets_separate() { +async fn host_views_carry_no_idmap_and_only_cifs_forces_an_owner() { let id = SharedVolumeId::new(); - let definition = SourceDefinition::new(SharedVolumeSource::Local, None); - let path = local_path(crate::PACKAGE_DATA, &id); - let mapped = definition.filesystem(&id); - let expected = IdMapped::new(Bind::new(&path), vec![crate::lxc::BASE_IDMAP]); + let local = SourceDefinition::new(SharedVolumeSource::Local, None); + assert!(local.stores_container_ids()); assert_eq!( - mapped.source_hash().await.unwrap(), - expected.source_hash().await.unwrap() + local.filesystem(&id).source_hash().await.unwrap(), + Bind::new(local_path(crate::PACKAGE_DATA, &id)) + .source_hash() + .await + .unwrap() + ); + let device = tempfile::NamedTempFile::new().unwrap(); + let disk = SourceDefinition::new( + SharedVolumeSource::Disk { + logicalname: device.path().to_owned(), + path: "data".into(), + drive: None, + }, + None, + ); + assert!(disk.stores_container_ids()); + assert_eq!( + disk.filesystem(&id).source_hash().await.unwrap(), + BlockDev::new(device.path().to_owned()) + .source_hash() + .await + .unwrap() + ); + let cifs = SourceDefinition::new( + SharedVolumeSource::Cifs { + hostname: "nas.local".into(), + path: "share".into(), + username: "user".into(), + }, + Some(SharedVolumeCredentials { + password: Some("secret".into()), + }), + ); + assert!(!cifs.stores_container_ids()); + assert_eq!( + cifs.filesystem(&id).source_hash().await.unwrap(), + SharedCifs(cifs.cifs().unwrap()) + .source_hash() + .await + .unwrap() ); - let raw = PreparedFilesystem::<_, BlockDev, Cifs>::Local(LocalSubvolume(path)); - for access in [ReadOnly, ReadWrite] { - assert_ne!( - mapped.mount_hash(access).await.unwrap(), - raw.mount_hash(access).await.unwrap() - ); - } } #[tokio::test] @@ -52,7 +81,7 @@ async fn failed_publications_remove_new_directories_and_successful_ones_preserve #[tokio::test] #[ignore = "requires root, BTRFS_TEST_VOLUMES_DIR and a private Linux mount namespace"] -async fn local_creation_maps_owners_without_shifting_persisted_ids() { +async fn local_creation_keeps_container_ids_on_the_host_view() { use std::os::unix::fs::{MetadataExt, PermissionsExt}; let fixture = crate::util::btrfs::tests::directory(); let path = fixture.path().join("volume"); @@ -68,13 +97,9 @@ async fn local_creation_maps_owners_without_shifting_persisted_ids() { .await .unwrap(); let root = std::fs::metadata(view.path()).unwrap(); - assert_eq!((root.uid(), root.gid()), (100000, 100000)); - let mapped_file = view.path().join("owner"); - let metadata = std::fs::metadata(&mapped_file).unwrap(); - assert_eq!((metadata.uid(), metadata.gid()), (101000, 102000)); - std::os::unix::fs::chown(&mapped_file, Some(103000), Some(104000)).unwrap(); - let metadata = std::fs::metadata(&file).unwrap(); - assert_eq!((metadata.uid(), metadata.gid()), (3000, 4000)); + assert_eq!((root.uid(), root.gid()), (0, 0)); + let metadata = std::fs::metadata(view.path().join("owner")).unwrap(); + assert_eq!((metadata.uid(), metadata.gid()), (1000, 2000)); view.unmount().await.unwrap(); tokio::fs::write(path.join("sentinel"), b"allocated data") .await @@ -457,9 +482,16 @@ async fn external_folder_is_created_pinned_and_limits_consumer_subpaths() { let consumer_root = tempfile::tempdir().unwrap(); std::fs::set_permissions(consumer_root.path(), std::fs::Permissions::from_mode(0o755)).unwrap(); let consumer_path = consumer_root.path().join("volume"); - let consumer = MountGuard::mount(&Bind::new(source.path()), &consumer_path, ReadWrite) - .await - .unwrap(); + let consumer = MountGuard::mount( + &crate::disk::mount::filesystem::idmapped::IdMapped::new( + Bind::new(source.path()), + vec![crate::lxc::BASE_IDMAP], + ), + &consumer_path, + ReadWrite, + ) + .await + .unwrap(); let uid = crate::lxc::BASE_IDMAP.to_id.to_string(); tokio::process::Command::new("setpriv") .args([ @@ -549,14 +581,20 @@ async fn external_partition_maps_service_ownership_without_changing_disk_owners( b"external-preserved\n" ); let metadata = std::fs::metadata(mapped.path()).unwrap(); - assert_eq!(metadata.uid(), crate::lxc::BASE_IDMAP.to_id); - assert_eq!(metadata.gid(), crate::lxc::BASE_IDMAP.to_id); + assert_eq!((metadata.uid(), metadata.gid()), (0, 0)); let consumer_root = tempfile::tempdir().unwrap(); std::fs::set_permissions(consumer_root.path(), std::fs::Permissions::from_mode(0o755)).unwrap(); let consumer_path = consumer_root.path().join("volume"); - let consumer = MountGuard::mount(&Bind::new(mapped.path()), &consumer_path, ReadWrite) - .await - .unwrap(); + let consumer = MountGuard::mount( + &crate::disk::mount::filesystem::idmapped::IdMapped::new( + Bind::new(mapped.path()), + vec![crate::lxc::BASE_IDMAP], + ), + &consumer_path, + ReadWrite, + ) + .await + .unwrap(); let uid = crate::lxc::BASE_IDMAP.to_id.to_string(); tokio::process::Command::new("setpriv") .args([ From f89e1b356d14a92b80c878428558e6834ced8add Mon Sep 17 00:00:00 2001 From: Helix the Red <355572797+helix-red@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:40:48 -0700 Subject: [PATCH 16/38] ci: build the container-runtime rootfs natively, upload compressed artifacts unzipped, ship the Pi image gzipped (#4795) * ci(start-os): build the container-runtime rootfs in the native image job compiled-.tar carried rootfs..squashfs, whose build runs apt in a target-architecture chroot. The riscv64 build job runs on an x86 runner, so that step ran under QEMU. The tarball now carries the container-runtime dist instead, and startos-image.yaml, which already runs on a native runner for every platform, assembles the rootfs. The rootfs scripts and units join OS_IMAGE_PATHS so pull requests touching them still build images. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * ci: upload already-compressed artifacts without zipping Images (squashfs, iso, img, migration squashfs), product debs and s9pks are uploaded with archive: false, so each artifact is the file itself and is named after it. Downloads match those file names by pattern, and the release tooling fetches them through a REST helper because gh run download cannot fetch unarchived artifacts (cli/cli#13012). Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * Proposed changes for #4796 Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(start-os): extract the container-runtime base instead of loop-mounting it The riscv64 image runner's kernel cannot mount squashfs, so building the rootfs there failed at the base mount. update-image.sh now unpacks the base with unsquashfs and builds in the extracted tree, which also drops the overlay. update-image-local.sh stops when its container fails rather than letting make continue without a rootfs. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * ci(start-os): hand off compiled artifacts as an unzipped tar.gz The build job's compiled-.tar exists only to keep the binaries' execute bits, which a zipped artifact drops. It is now gzipped and uploaded with archive: false, so the artifact is that file as-is rather than a zip around a tar; the image job downloads it by its filename. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * ci(start-os): ship the Pi image as an unzipped img.gz The raspberrypi image job gzips its .img and uploads the .img.gz with archive: false. The deploy leg and manage-release.sh pull-gha gunzip it for the raw image the registry indexes and signs; pull-gha keeps CI's .gz, which the release publishes beside the bare image. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * Proposed changes for #4795 Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * fix(ci): bound artifact discovery by creation age, not expiry Adopts @helix-white's proposal to skip expired matches rather than stop at the first one, since expiry does not follow listing order. Both callers read the whole output, so discovery instead stops at the first artifact created over 15 days ago, past the 14-day retention of every artifact it searches. The fixtures give rerun artifacts their own creation time. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * ci(start-wrt): upload the flashable images unzipped The image job uploads each StartWRT .img.gz as its own artifact with archive: false, through the repo's upload-each action. The deploy downloads them by pattern and checks that both the sdcard and the sysupgrade image are present, and manage-release.sh pull-gha fetches them with gha-artifact-download.sh, since gh run download cannot. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(ci): share one artifact discovery across the deb products Adopts @helix-white's proposal: apt-publish-alpha makes one gha-artifact-run-ids.sh call with an extended glob over its product list rather than one per product, so each publication reads the artifact listing once. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * ci(start-os): build the container-runtime rootfs once per architecture A rootfs job in build-products.yaml builds rootfs..squashfs on a native runner for each architecture and uploads it unzipped; the image jobs and the publish run download it instead of each rebuilding it, so x86_64 and aarch64 no longer build it three and four times. The RISC-V action-runtime bootstrap and the compiled-tarball unpacking move into local composite actions shared by the image and rootfs jobs. The bootstrap now runs right after checkout, ahead of every other JavaScript action, since checkout transfers no artifacts. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(ci): let the rootfs job download its compiled tarball Adopts @helix-white's proposal: downloading an artifact by run id needs actions: read, which the rootfs job's explicit permissions dropped. The shared action records the requirement, and a test covers every compiled-artifact consumer. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * ci(start-os): publish the Pi image gzipped only The deploy uploads the raspberrypi .img.gz and indexes it in the registry's img slot through a hardlink named for the slot, like StartWRT's images; no raw .img is uploaded. manage-release.sh signs and checksums the .img.gz, the release notes link the indexed URL, and push-gz, ensure_img_gz and the .gz handling in pull and pull-gha are gone. start-cli's 'registry os asset get' now names a download .gz when its URLs serve a .gz file, so gzipped images (StartOS's and StartWRT's) are no longer saved as .img. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(release): keep legacy raw Pi images signed and checksummed Adopts @helix-white's proposal: a version indexed with a raw .img before the gzip-only switch still releases with that image in its checksums and signatures, and only a .gz link carries the gzip tooltip. Adds the StartOS and start-cli changelog fragments and drops the gzip-copy wording from the prerelease docs. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * revert(release): drop legacy raw Pi image handling This merges before the next StartOS release is built, so no released version carries a raw .img entry: release files and the gzip tooltip cover the .img.gz only. Keeps the changelog fragments and the doc wording from the previous commit. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --------- Co-authored-by: helix-white <267227783+helix-a@users.noreply.github.com> --- .forgejo/workflows/release.yml | 16 +- .../actions/riscv-action-runtime/action.yml | 40 ++++ .../actions/tests/apt-publish-alpha.test.mjs | 81 ++++++-- .../actions/tests/changed-products.test.mjs | 7 + .github/actions/tests/publisher-cli.test.mjs | 87 ++++++++- .github/actions/tests/startos-deploy.test.mjs | 108 +++++++++++ .../actions/tests/startos-runners.test.mjs | 37 +++- .../actions/tests/workflow-variants.test.mjs | 10 +- .github/actions/upload-each/action.yml | 4 + .github/actions/upload-each/dist/index.js | 2 +- .github/actions/upload-each/src/index.js | 3 +- .../actions/upload-each/test/index.test.cjs | 11 ++ .../actions/use-compiled-artifacts/action.yml | 45 +++++ .github/scripts/changed-products.mjs | 2 + .github/workflows/apt-publish-alpha.yml | 13 +- .github/workflows/build-products.yaml | 78 ++++++-- .github/workflows/build.yml | 2 +- .github/workflows/release.yml | 22 +-- .github/workflows/start-wrt.yaml | 23 ++- .github/workflows/startos-image.yaml | 155 +++++++--------- .github/workflows/startos-iso.yaml | 10 +- .gitignore | 2 +- AGENTS.md | 4 +- Makefile | 2 +- debian/publish.sh | 2 - ...atch-fixed-gzipped-image-download-names.md | 5 + projects/start-os/AGENTS.md | 2 +- projects/start-os/build.mk | 14 +- .../patch-changed-raspberrypi-image-format.md | 5 + projects/start-os/container-runtime/AGENTS.md | 1 + .../container-runtime/ARCHITECTURE.md | 2 +- .../container-runtime/update-image-local.sh | 2 + .../container-runtime/update-image.sh | 5 +- scripts/generate-forgejo-workflows.cjs | 3 +- scripts/gha-artifact-download.sh | 27 +++ scripts/gha-artifact-run-ids.sh | 32 +++- scripts/gha-image-run.sh | 7 +- scripts/manage-release.sh | 175 +++--------------- scripts/tests/gha-artifact-download-test.mjs | 63 +++++++ scripts/tests/gha-artifact-fixture.mjs | 31 +++- scripts/tests/gha-artifact-run-ids-test.mjs | 67 +++++-- scripts/tests/gha-image-run-test.mjs | 30 ++- scripts/tests/prerelease-test.mjs | 4 - scripts/tests/release-images-test.sh | 71 +++++++ scripts/tests/release-resume-test.sh | 78 -------- scripts/update-from-gha.sh | 10 +- .../start-core/src/registry/os/asset/get.rs | 55 +++++- 47 files changed, 970 insertions(+), 485 deletions(-) create mode 100644 .github/actions/riscv-action-runtime/action.yml create mode 100644 .github/actions/use-compiled-artifacts/action.yml create mode 100644 projects/start-cli/changelog/patch-fixed-gzipped-image-download-names.md create mode 100644 projects/start-os/changelog/patch-changed-raspberrypi-image-format.md create mode 100755 scripts/gha-artifact-download.sh create mode 100644 scripts/tests/gha-artifact-download-test.mjs create mode 100644 scripts/tests/release-images-test.sh delete mode 100644 scripts/tests/release-resume-test.sh diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index 9164ea76b8..1b2a1dd0d8 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -99,14 +99,14 @@ jobs: uses: https://github.com/Start9Labs/start-technologies/.github/actions/build-s9pk@master with: target: ${{ matrix.target }} - - name: Upload s9pks for Publish stage + - name: Upload s9pks uses: https://data.forgejo.org/forgejo/upload-artifact@v4 with: - name: build-${{ matrix.target || 'default' }} - path: ./*.s9pk if-no-files-found: error + retention-days: 14 compression-level: 0 - retention-days: 1 + name: s9pks-${{ matrix.target || 'default' }} + path: '*.s9pk' Publish: needs: BuildMatrix runs-on: ubuntu-latest @@ -131,7 +131,6 @@ jobs: - name: Collect s9pks from BuildMatrix uses: https://data.forgejo.org/forgejo/download-artifact@v4 with: - pattern: build-* merge-multiple: true path: . - name: Verify s9pks @@ -312,10 +311,3 @@ jobs: start-cli --registry "$REGISTRY" registry package add "$s9pk" --url "${GH_URL}/${s9pk}" done shell: bash - - name: Upload s9pks - uses: https://data.forgejo.org/forgejo/upload-artifact@v4 - with: - retention-days: 14 - compression-level: 0 - name: s9pks - path: '*.s9pk' diff --git a/.github/actions/riscv-action-runtime/action.yml b/.github/actions/riscv-action-runtime/action.yml new file mode 100644 index 0000000000..01550f1c6b --- /dev/null +++ b/.github/actions/riscv-action-runtime/action.yml @@ -0,0 +1,40 @@ +name: RISC-V action runtime +description: >- + Replaces the runner's bundled action Node with the requested release, run + `--single-threaded`. V8's background threads corrupt the heap on the riscv64 + runners during large artifact transfers. Leaves the runtime untouched when the + download or probe fails. +inputs: + nodejs-version: + description: Node release to install + required: true +runs: + using: composite + steps: + # Actions use the runner's bundled Node, not the Node on GITHUB_PATH. + # Its wrapper is bash; dash drops hyphenated `INPUT_*` variables. + - shell: bash + env: + NODEJS_VERSION: ${{ inputs.nodejs-version }} + run: | + set -euo pipefail + worker="$(readlink -f "/proc/$PPID/exe")" + test "$(basename "$worker")" = Runner.Worker + runner_node="$(dirname "$worker")/../externals/node24/bin/node" + echo "Bundled action runtime: $("$runner_node" --version)" + base="https://unofficial-builds.nodejs.org/download/release/v${NODEJS_VERSION}" + tarball="node-v${NODEJS_VERSION}-linux-riscv64.tar.xz" + cd "$RUNNER_TEMP" + curl -fsSLO "$base/$tarball" + curl -fsSL "$base/SHASUMS256.txt" | grep " $tarball\$" | sha256sum -c - + tar -xJf "$tarball" + node_dir="$RUNNER_TEMP/${tarball%.tar.xz}" + test "$("$node_dir/bin/node" --version)" = "v${NODEJS_VERSION}" + "$node_dir/bin/node" --single-threaded -e 'require("node:crypto").createHash("sha256").update("action-runtime").digest(); console.log(process.versions)' + install -m 755 "$node_dir/bin/node" "$runner_node.real.next" + mv -f "$runner_node.real.next" "$runner_node.real" + printf '#!/bin/bash\nexec "%s" --single-threaded "$@"\n' "$runner_node.real" > "$runner_node.next" + chmod 755 "$runner_node.next" + mv -f "$runner_node.next" "$runner_node" + echo "Updated action runtime: $("$runner_node" --version)" + echo "$node_dir/bin" >> "$GITHUB_PATH" diff --git a/.github/actions/tests/apt-publish-alpha.test.mjs b/.github/actions/tests/apt-publish-alpha.test.mjs index b1ab8d2d30..26b439b0cf 100644 --- a/.github/actions/tests/apt-publish-alpha.test.mjs +++ b/.github/actions/tests/apt-publish-alpha.test.mjs @@ -17,8 +17,11 @@ const ARCHES = ['x86_64', 'aarch64', 'riscv64'] const daysAgo = days => new Date(Date.now() - days * 86400e3).toISOString().replace(/\.\d+Z$/, 'Z') +const deb = (product, arch) => `${product}-0.4.0-aaaaaaa_${arch}.deb` const debs = (product, arches = ARCHES) => - arches.map(arch => `${product}_${arch}.deb`) + arches.map(arch => deb(product, arch)) +const downloaded = (runId, product) => + ARCHES.map(arch => `${runId} ${deb(product, arch)}`) const run = (id, created, artifacts, overrides = {}) => ({ id, created_at: created, @@ -64,11 +67,14 @@ test('each product comes from its newest master build holding every arch', t => }), ]) assert.equal(result.status, 0, result.stdout + result.stderr) - assert.deepEqual(downloads.sort(), [ - '1 start-registry_*.deb', - '1 start-tunnel_*.deb', - '2 start-cli_*.deb', - ]) + assert.deepEqual( + downloads.sort(), + [ + ...downloaded(1, 'start-registry'), + ...downloaded(1, 'start-tunnel'), + ...downloaded(2, 'start-cli'), + ].sort(), + ) }) test('PR-only activity does not hide complete master artifacts', t => { @@ -83,11 +89,45 @@ test('PR-only activity does not hide complete master artifacts', t => { ), ]) assert.equal(result.status, 0, result.stdout + result.stderr) - assert.deepEqual(downloads.sort(), [ - '1 start-cli_*.deb', - '1 start-registry_*.deb', - '1 start-tunnel_*.deb', + assert.deepEqual( + downloads.sort(), + [ + ...downloaded(1, 'start-cli'), + ...downloaded(1, 'start-registry'), + ...downloaded(1, 'start-tunnel'), + ].sort(), + ) +}) + +test('all products share one paginated artifact discovery', t => { + const { result, downloads, calls } = collectFrom(t, [ + run(1, daysAgo(2), [ + ...debs('start-cli'), + ...debs('start-tunnel'), + ...debs('start-registry'), + ]), + run( + 2, + daysAgo(1), + Array.from({ length: 201 }, (_, index) => `unrelated-${index}`), + ), ]) + assert.equal(result.status, 0, result.stdout + result.stderr) + assert.deepEqual( + downloads.sort(), + [ + ...downloaded(1, 'start-cli'), + ...downloaded(1, 'start-tunnel'), + ...downloaded(1, 'start-registry'), + ].sort(), + ) + const listings = calls.flatMap(args => + args.filter(arg => + arg.startsWith(`repos/${REPOSITORY}/actions/artifacts?`), + ), + ) + assert.ok(listings.length > 1) + assert.equal(listings.length, new Set(listings).size) }) test('a product without a complete build keeps its published package', t => { @@ -95,11 +135,11 @@ test('a product without a complete build keeps its published package', t => { run(1, daysAgo(3), [ ...debs('start-cli'), ...debs('start-registry', ['x86_64']), - { name: 'start-tunnel_x86_64.deb', expired: true }, + { name: deb('start-tunnel', 'x86_64'), expired: true }, ]), ]) assert.equal(result.status, 0, result.stdout + result.stderr) - assert.deepEqual(downloads, ['1 start-cli_*.deb']) + assert.deepEqual(downloads.sort(), downloaded(1, 'start-cli').sort()) assert.match(result.stdout, /start-tunnel has no complete master build left/) assert.match( result.stdout, @@ -122,21 +162,24 @@ test('an older run with unexpired rerun artifacts remains eligible', t => { ...debs('start-cli'), ...debs('start-tunnel'), ...debs('start-registry'), - ], + ].map(name => ({ name, created_at: daysAgo(1) })), { run_attempt: 2 }, ), ]) assert.equal(result.status, 0, result.stdout + result.stderr) - assert.deepEqual(downloads.sort(), [ - '1 start-cli_*.deb', - '1 start-registry_*.deb', - '1 start-tunnel_*.deb', - ]) + assert.deepEqual( + downloads.sort(), + [ + ...downloaded(1, 'start-cli'), + ...downloaded(1, 'start-registry'), + ...downloaded(1, 'start-tunnel'), + ].sort(), + ) }) test('expired artifacts do not cause run metadata queries', t => { const { result, calls } = collectFrom(t, [ - run(1, daysAgo(20), [{ name: 'start-cli_x86_64.deb', expired: true }]), + run(1, daysAgo(20), [{ name: deb('start-cli', 'x86_64'), expired: true }]), ]) assert.notEqual(result.status, 0) assert.equal( diff --git a/.github/actions/tests/changed-products.test.mjs b/.github/actions/tests/changed-products.test.mjs index 44c90501b0..1f4e7db642 100644 --- a/.github/actions/tests/changed-products.test.mjs +++ b/.github/actions/tests/changed-products.test.mjs @@ -41,6 +41,13 @@ for (const [path, push, pullRequest = push, osImage = false] of [ true, ], ['projects/start-os/startd.service', ['start-os'], undefined, true], + [ + 'projects/start-os/container-runtime/deb-install.sh', + ['start-os'], + undefined, + true, + ], + ['projects/start-os/container-runtime/src/index.ts', ['start-os']], ['projects/start-os/src/main.rs', ['start-os']], ['projects/start-os/docs/src/overview.md', []], ['projects/start-os/release-notes/0.4.1.md', ['start-os'], undefined, true], diff --git a/.github/actions/tests/publisher-cli.test.mjs b/.github/actions/tests/publisher-cli.test.mjs index 314e6f059f..586224b9a9 100644 --- a/.github/actions/tests/publisher-cli.test.mjs +++ b/.github/actions/tests/publisher-cli.test.mjs @@ -454,7 +454,7 @@ test('every product builds from one compile per target, on standard runners', () ) assert.ok(compile !== -1) for (const [product, recipe] of [ - ['start-os', 'make compiled-${{ matrix.arch }}.tar'], + ['start-os', 'make compiled-${{ matrix.arch }}.tar.gz'], ['start-cli', 'make start-cli-deb'], ['start-registry', 'make start-registry-deb'], ['start-tunnel', 'make start-tunnel-deb'], @@ -483,7 +483,7 @@ test('the CLI binaries cover every triple a release attaches', () => { const linux = products.jobs.build.steps.find( step => step.uses === 'actions/upload-artifact@v7' && - step.with.name.endsWith('-unknown-linux-musl'), + step.with.name?.endsWith('-unknown-linux-musl'), ) const built = [ ...['x86_64', 'aarch64', 'riscv64'].map(arch => @@ -502,6 +502,37 @@ test('the CLI binaries cover every triple a release attaches', () => { ) }) +test('registry image platforms match the downloaded deb architectures', t => { + const mapPlatforms = step( + products.jobs['registry-image'], + 'Map matrix.arch to docker platform', + ).run + for (const [arches, expected] of [ + [['x86_64'], ['linux/amd64']], + [['aarch64'], ['linux/arm64']], + [['riscv64'], ['linux/riscv64']], + [ + ['x86_64', 'aarch64', 'riscv64'], + ['linux/amd64', 'linux/arm64', 'linux/riscv64'], + ], + ]) { + const f = fixture(t) + for (const arch of arches) + f.write(`start-registry-0.4.0-aaaaaaa_${arch}.deb`, '') + const output = f.write('env', '') + const result = f.run('bash', ['-e', '-c', mapPlatforms], { + env: { ...f.env, GITHUB_ENV: output }, + encoding: 'utf8', + }) + assert.equal(result.status, 0, result.stdout + result.stderr) + const platforms = readFileSync(output, 'utf8') + .trim() + .replace(/^DOCKER_PLATFORM=/, '') + .split(',') + assert.deepEqual(platforms.sort(), expected.sort()) + } +}) + test('build environments: release-equivalent on master and NONE, dev elsewhere', () => { for (const [event, input, ref, expected] of [ ['push', {}, 'refs/heads/master', ''], @@ -523,15 +554,19 @@ test('build environments: release-equivalent on master and NONE, dev elsewhere', test('a publishing build dispatches startos-iso.yaml pinned to its commit', t => { const publish = products.jobs.publish - assert.deepEqual(publish.needs, ['changes', 'build']) - for (const [channel, build, expected] of [ + assert.deepEqual(publish.needs, ['changes', 'build', 'rootfs']) + for (const [channel, rootfs, expected] of [ ['alpha', 'success', true], ['', 'success', false], ['alpha', 'failure', false], + ['alpha', 'skipped', false], ]) assert.equal( evaluate(publish.if, { - needs: { changes: { outputs: { channel } }, build: { result: build } }, + needs: { + changes: { outputs: { channel } }, + rootfs: { result: rootfs }, + }, }), expected, ) @@ -803,3 +838,45 @@ test('product builds trigger on every push and pull request and classify in the } assert.deepEqual(wrt.jobs.deploy.needs, ['image']) }) + +test('the rootfs builds once per architecture for every image this run or its publish builds', () => { + const { image, rootfs } = products.jobs + assert.deepEqual(image.needs, ['changes', 'build', 'rootfs']) + for (const [event, osImage, channel, rootfsRuns, imageRuns] of [ + ['pull_request', 'true', '', true, true], + ['pull_request', 'false', '', false, false], + ['push', 'false', '', true, true], + ['push', 'false', 'alpha', true, false], + ]) { + const outputs = { 'start-os': 'true', 'os-image': osImage, channel } + const context = { + github: { event_name: event }, + needs: { + changes: { outputs }, + build: { result: 'success' }, + rootfs: { result: 'success' }, + }, + } + assert.equal(evaluate(rootfs.if, context), rootfsRuns, `${event} rootfs`) + assert.equal(evaluate(image.if, context), imageRuns, `${event} image`) + } + assert.equal( + evaluate(image.if, { + github: { event_name: 'push' }, + needs: { + changes: { outputs: { 'start-os': 'true', channel: '' } }, + rootfs: { result: 'failure' }, + }, + }), + false, + ) +}) + +test('compiled-artifact consumers grant Actions read permission', () => { + for (const permissions of [ + products.jobs.rootfs.permissions, + products.jobs.image.permissions, + iso.permissions, + ]) + assert.equal(permissions.actions, 'read') +}) diff --git a/.github/actions/tests/startos-deploy.test.mjs b/.github/actions/tests/startos-deploy.test.mjs index 41343dfb4b..c7d72278ff 100644 --- a/.github/actions/tests/startos-deploy.test.mjs +++ b/.github/actions/tests/startos-deploy.test.mjs @@ -457,3 +457,111 @@ for (const [name, deployed, published, status, warning] of [ assert.equal(f.run('test -e deleted.log').status, 1) }) } + +test('a deploy leg missing one of its images fails before uploading', t => { + const check = step(leg, 'Check downloaded images') + for (const [platform, files, ok] of [ + [PLATFORM, FILES, true], + [PLATFORM, [FILES[0]], false], + [ + PLATFORM, + [`startos-${VERSION}-aaaaaaa_${PLATFORM}-nonfree.iso`, FILES[0]], + false, + ], + [ + 'raspberrypi', + [ + `startos-${VERSION}-aaaaaaa_raspberrypi.squashfs`, + `startos-${VERSION}-aaaaaaa_raspberrypi.img.gz`, + ], + true, + ], + [ + 'raspberrypi', + [ + `startos-${VERSION}-aaaaaaa_raspberrypi.squashfs`, + `startos-${VERSION}-aaaaaaa_raspberrypi.img`, + ], + false, + ], + ['raspberrypi', [`startos-${VERSION}-aaaaaaa_raspberrypi.squashfs`], false], + ]) { + const f = fixture(t) + for (const file of files) f.write(`artifacts/${file}`, '') + const result = f.run('bash', ['-e', '-c', check], { + cwd: join(f.root, 'artifacts'), + env: { ...f.env, PLATFORM: platform }, + encoding: 'utf8', + }) + assert.equal( + result.status === 0, + ok, + `${platform} ${files}: ${result.stdout}`, + ) + } +}) + +test('a start-wrt deploy missing one of its images fails before uploading', t => { + const check = step( + load('start-wrt.yaml').jobs.deploy, + 'Check downloaded images', + ) + for (const [files, ok] of [ + [WRT_IMAGES, true], + [[WRT_IMAGES[0]], false], + [[WRT_IMAGES[1]], false], + ]) { + const f = fixture(t) + for (const file of files) f.write(`artifacts/${file}`, '') + const result = f.run('bash', ['-e', '-c', check], { + cwd: join(f.root, 'artifacts'), + env: f.env, + encoding: 'utf8', + }) + assert.equal(result.status === 0, ok, `${files}: ${result.stdout}`) + } +}) + +test('a raspberrypi deploy indexes its img gzipped and records the img.gz as published', t => { + const f = deployFixture(t, index({ [VERSION]: entry(SHA) })) + const pi = [ + `startos-${VERSION}-aaaaaaa_raspberrypi.squashfs`, + `startos-${VERSION}-aaaaaaa_raspberrypi.img.gz`, + ] + for (const file of pi) f.write(`artifacts/${file}`, `${file} built\n`) + const env = { PLATFORM: 'raspberrypi', RUNNER_TEMP: f.root } + const result = f.run(indexAssets, env, join(f.root, 'artifacts')) + assert.equal(result.status, 0, result.stdout + result.stderr) + const version = f.registry().versions[VERSION] + assert.deepEqual(version.img.raspberrypi.urls, [ + `https://cdn.example/v${VERSION}/${pi[1]}`, + ]) + assert.deepEqual(version.squashfs.raspberrypi.urls, [ + `https://cdn.example/v${VERSION}/${pi[0]}`, + ]) + const add = f + .calls() + .find( + call => + call.slice(0, 4).join(' ') === 'registry os asset add' && + call.some(arg => arg.endsWith('.img.gz')), + ) + const indexedFile = add.slice(4).find(arg => !arg.startsWith('--')) + assert.equal(indexedFile, pi[1].replace(/\.gz$/, '')) + assert.equal( + readFileSync(join(f.root, 'artifacts', indexedFile), 'utf8'), + `${pi[1]} built\n`, + ) + const recorded = f.run( + step(leg, 'Record published images'), + env, + join(f.root, 'artifacts'), + ) + assert.equal(recorded.status, 0, recorded.stderr) + assert.deepEqual( + readFileSync(join(f.root, 'published-raspberrypi.txt'), 'utf8') + .trim() + .split('\n'), + [pi[0], pi[1]], + ) +}) diff --git a/.github/actions/tests/startos-runners.test.mjs b/.github/actions/tests/startos-runners.test.mjs index 13f6ebe404..6c17f43271 100644 --- a/.github/actions/tests/startos-runners.test.mjs +++ b/.github/actions/tests/startos-runners.test.mjs @@ -17,8 +17,15 @@ const runners = yaml.load(image['runs-on'].match(/fromJson\('([\s\S]*?)'\)/)[1]) const architectures = yaml.load( image.env.ARCH.match(/fromJson\('([\s\S]*?)'\)/)[1], ) -const bootstrap = image.steps.find( - step => step.name === 'Update RISC-V action runtime', +const bootstrap = yaml.load( + readFileSync( + new URL('../riscv-action-runtime/action.yml', import.meta.url), + 'utf8', + ), +).runs.steps[0] +const rootfs = products.jobs.rootfs +const rootfsRunners = yaml.load( + rootfs['runs-on'].match(/fromJson\('([\s\S]*?)'\)/)[1], ) for (const platform of ['riscv64', 'riscv64-nonfree']) { @@ -28,10 +35,28 @@ for (const platform of ['riscv64', 'riscv64-nonfree']) { }) } -test('the native runtime bootstrap precedes every JavaScript action', () => { - assert.ok(bootstrap) - assert.ok(image.steps.indexOf(bootstrap) < image.steps.findIndex(s => s.uses)) - assert.equal(bootstrap.if, "${{ env.ARCH == 'riscv64' }}") +test('each architecture builds its container runtime rootfs natively', () => { + assert.deepEqual(rootfsRunners, { + x86_64: 'ubuntu-latest', + aarch64: 'ubuntu-24.04-arm', + riscv64: 'ubuntu-24.04-riscv', + }) + for (const [platform, arch] of Object.entries(architectures)) + assert.equal(rootfsRunners[arch], runners[platform], platform) +}) + +test('the native runtime bootstrap precedes every JavaScript action after checkout', () => { + for (const [job, arch] of [ + [image, 'env.ARCH'], + [rootfs, 'matrix.arch'], + ]) { + const actions = job.steps.filter(step => step.uses) + assert.equal(actions[0].uses, 'actions/checkout@v6') + assert.equal(actions[1].uses, './.github/actions/riscv-action-runtime') + assert.equal(actions[1].if, `\${{ ${arch} == 'riscv64' }}`) + assert.equal(actions[1].with['nodejs-version'], '${{ env.NODEJS_VERSION }}') + } + assert.equal(bootstrap.env.NODEJS_VERSION, '${{ inputs.nodejs-version }}') for (const caller of [workflow, products]) assert.equal( caller.jobs.image.with['nodejs-version'], diff --git a/.github/actions/tests/workflow-variants.test.mjs b/.github/actions/tests/workflow-variants.test.mjs index 8adedb1c48..4d71aaeb9b 100644 --- a/.github/actions/tests/workflow-variants.test.mjs +++ b/.github/actions/tests/workflow-variants.test.mjs @@ -92,13 +92,15 @@ test('remote calls and their inner jobs select the x86 runner for emulated build test('Forgejo artifacts use compatible actions and preserve the build-to-publish handoff', () => { const release = document('.forgejo/workflows/release.yml') const upload = release.jobs.BuildMatrix.steps.find( - step => step.name === 'Upload s9pks for Publish stage', + step => step.name === 'Upload s9pks', ) assert.equal( upload.uses, 'https://data.forgejo.org/forgejo/upload-artifact@v4', ) - assert.equal(upload.with.name, "build-${{ matrix.target || 'default' }}") + assert.equal(upload.with.name, "s9pks-${{ matrix.target || 'default' }}") + assert.equal(upload.with.archive, undefined) + assert.equal(upload.with['compression-level'], 0) const download = release.jobs.Publish.steps.find( step => step.name === 'Collect s9pks from BuildMatrix', ) @@ -106,7 +108,7 @@ test('Forgejo artifacts use compatible actions and preserve the build-to-publish download.uses, 'https://data.forgejo.org/forgejo/download-artifact@v4', ) - assert.equal(download.with.pattern, 'build-*') + assert.equal(download.with.pattern, undefined) assert.equal(download.with['merge-multiple'], true) const build = document('.forgejo/workflows/build.yml') assert.equal( @@ -117,6 +119,8 @@ test('Forgejo artifacts use compatible actions and preserve the build-to-publish build.jobs.BuildMatrix.steps.at(-1).with.name, "s9pks-${{ matrix.target || 'default' }}", ) + assert.equal(build.jobs.BuildMatrix.steps.at(-1).with.archive, undefined) + assert.equal(build.jobs.BuildMatrix.steps.at(-1).with['compression-level'], 0) }) test('Forgejo releases use the in-place Forgejo publisher and caller credentials', () => { diff --git a/.github/actions/upload-each/action.yml b/.github/actions/upload-each/action.yml index d69e39351a..fb9b3e4fc0 100644 --- a/.github/actions/upload-each/action.yml +++ b/.github/actions/upload-each/action.yml @@ -12,6 +12,10 @@ inputs: description: 'Zip compression level passed to @actions/artifact (0-9).' required: false default: '6' + archive: + description: 'Zip each file before upload. When false, each artifact is the file itself and compression-level is ignored.' + required: false + default: 'true' if-no-files-found: description: 'Behavior when the glob matches nothing: warn | error | ignore.' required: false diff --git a/.github/actions/upload-each/dist/index.js b/.github/actions/upload-each/dist/index.js index 471a5a78fe..48f6bab346 100644 --- a/.github/actions/upload-each/dist/index.js +++ b/.github/actions/upload-each/dist/index.js @@ -89,4 +89,4 @@ const og=32;const ag=9;const Ag=59;const cg=61;const lg=34;const ug=92;const dg= ()=>new ArrayBuffer(0)))}}function isJSONResponse(e){return e.type==="application/json"||e.type==="application/scim+json"}function toErrorMessage(e){if(typeof e==="string"){return e}if(e instanceof ArrayBuffer){return"Unknown error"}if(typeof e==="object"&&e!==null&&"message"in e){const t=e;const r="documentation_url"in t?` - ${t.documentation_url}`:"";return Array.isArray(t.errors)?`${t.message}: ${t.errors.map((e=>JSON.stringify(e))).join(", ")}${r}`:`${t.message}${r}`}return`Unknown error: ${JSON.stringify(e)}`}function dist_bundle_withDefaults(e,t){const r=e.defaults(t);const newApi=function(e,t){const n=r.merge(e,t);if(!n.request||!n.request.hook){return fetchWrapper(r.parse(n))}const request2=(e,t)=>fetchWrapper(r.parse(r.merge(e,t)));Object.assign(request2,{endpoint:r,defaults:dist_bundle_withDefaults.bind(null,r)});return n.request.hook(request2,n)};return Object.assign(newApi,{endpoint:r,defaults:dist_bundle_withDefaults.bind(null,r)})}var Ug=dist_bundle_withDefaults(ig,Mg); /* v8 ignore next -- @preserve */ /* v8 ignore else -- @preserve */var Lg="0.0.0-development";function _buildMessageForResponseErrors(e){return`Request failed due to following response errors:\n`+e.errors.map((e=>` - ${e.message}`)).join("\n")}var _g=class extends Error{constructor(e,t,r){super(_buildMessageForResponseErrors(r));this.request=e;this.headers=t;this.response=r;this.errors=r.errors;this.data=r.data;if(Error.captureStackTrace){Error.captureStackTrace(this,this.constructor)}}request;headers;response;name="GraphqlResponseError";errors;data};var Pg=["method","baseUrl","url","headers","request","query","mediaType","operationName"];var Og=["query","method","url"];var Hg=/\/api\/v3\/?$/;function graphql(e,t,r){if(r){if(typeof t==="string"&&"query"in r){return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`))}for(const e in r){if(!Og.includes(e))continue;return Promise.reject(new Error(`[@octokit/graphql] "${e}" cannot be used as variable name`))}}const n=typeof t==="string"?Object.assign({query:t},r):t;const s=Object.keys(n).reduce(((e,t)=>{if(Pg.includes(t)){e[t]=n[t];return e}if(!e.variables){e.variables={}}e.variables[t]=n[t];return e}),{});const i=n.baseUrl||e.endpoint.DEFAULTS.baseUrl;if(Hg.test(i)){s.url=i.replace(Hg,"/api/graphql")}return e(s).then((e=>{if(e.data.errors){const t={};for(const r of Object.keys(e.headers)){t[r]=e.headers[r]}throw new _g(s,t,e.data)}return e.data.data}))}function graphql_dist_bundle_withDefaults(e,t){const r=e.defaults(t);const newApi=(e,t)=>graphql(r,e,t);return Object.assign(newApi,{defaults:graphql_dist_bundle_withDefaults.bind(null,r),endpoint:r.endpoint})}var Gg=graphql_dist_bundle_withDefaults(Ug,{headers:{"user-agent":`octokit-graphql.js/${Lg} ${getUserAgent()}`},method:"POST",url:"/graphql"});function withCustomRequest(e){return graphql_dist_bundle_withDefaults(e,{method:"POST",url:"/graphql"})} -/* v8 ignore if -- @preserve */var Yg="(?:[a-zA-Z0-9_-]+)";var Vg="\\.";var Jg=new RegExp(`^${Yg}${Vg}${Yg}${Vg}${Yg}$`);var qg=Jg.test.bind(Jg);async function auth(e){const t=qg(e);const r=e.startsWith("v1.")||e.startsWith("ghs_");const n=e.startsWith("ghu_");const s=t?"app":r?"installation":n?"user-to-server":"oauth";return{type:"token",token:e,tokenType:s}}function withAuthorizationPrefix(e){if(e.split(/\./).length===3){return`bearer ${e}`}return`token ${e}`}async function hook(e,t,r,n){const s=t.endpoint.merge(r,n);s.headers.authorization=withAuthorizationPrefix(e);return t(s)}var Wg=function createTokenAuth2(e){if(!e){throw new Error("[@octokit/auth-token] No token passed to createTokenAuth")}if(typeof e!=="string"){throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string")}e=e.replace(/^(token|bearer) +/i,"");return Object.assign(auth.bind(null,e),{hook:hook.bind(null,e)})};const zg="7.0.8";const dist_src_noop=()=>{};const jg=console.warn.bind(console);const Kg=console.error.bind(console);function createLogger(e={}){if(typeof e.debug!=="function"){e.debug=dist_src_noop}if(typeof e.info!=="function"){e.info=dist_src_noop}if(typeof e.warn!=="function"){e.warn=jg}if(typeof e.error!=="function"){e.error=Kg}return e}const Zg=`octokit-core.js/${zg} ${getUserAgent()}`;class Octokit{static VERSION=zg;static defaults(e){const t=class extends(this){constructor(...t){const r=t[0]||{};if(typeof e==="function"){super(e(r));return}super(Object.assign({},e,r,r.userAgent&&e.userAgent?{userAgent:`${r.userAgent} ${e.userAgent}`}:null))}};return t}static plugins=[];static plugin(...e){const t=this.plugins;const r=class extends(this){static plugins=t.concat(e.filter((e=>!t.includes(e))))};return r}constructor(e={}){const t=new eg.Collection;const r={baseUrl:Ug.endpoint.DEFAULTS.baseUrl,headers:{},request:Object.assign({},e.request,{hook:t.bind(null,"request")}),mediaType:{previews:[],format:""}};r.headers["user-agent"]=e.userAgent?`${e.userAgent} ${Zg}`:Zg;if(e.baseUrl){r.baseUrl=e.baseUrl}if(e.previews){r.mediaType.previews=e.previews}if(e.timeZone){r.headers["time-zone"]=e.timeZone}this.request=Ug.defaults(r);this.graphql=withCustomRequest(this.request).defaults(r);this.log=createLogger(e.log);this.hook=t;if(!e.authStrategy){if(!e.auth){this.auth=async()=>({type:"unauthenticated"})}else{const r=Wg(e.auth);t.wrap("request",r.hook);this.auth=r}}else{const{authStrategy:r,...n}=e;const s=r(Object.assign({request:this.request,log:this.log,octokit:this,octokitOptions:n},e.auth));t.wrap("request",s.hook);this.auth=s}const n=this.constructor;for(let t=0;t({async next(){if(!a)return{done:true};try{const e=await s({method:i,url:a,headers:o});const t=normalizePaginatedListResponse(e);a=((t.headers.link||"").match(/<([^<>]+)>;\s*rel="next"/)||[])[1];if(!a&&"total_commits"in t.data){const e=new URL(t.url);const r=e.searchParams;const n=parseInt(r.get("page")||"1",10);const s=parseInt(r.get("per_page")||"250",10);if(n*s{if(s.done){return t}let i=false;function done(){i=true}t=t.concat(n?n(s.value,done):s.value.data);if(i){return t}return gather(e,t,r,n)}))}var sf=Object.assign(paginate,{iterator:iterator});var of=null&&["GET /advisories","GET /app/hook/deliveries","GET /app/installation-requests","GET /app/installations","GET /assignments/{assignment_id}/accepted_assignments","GET /classrooms","GET /classrooms/{classroom_id}/assignments","GET /enterprises/{enterprise}/code-security/configurations","GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories","GET /enterprises/{enterprise}/dependabot/alerts","GET /enterprises/{enterprise}/teams","GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships","GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations","GET /events","GET /gists","GET /gists/public","GET /gists/starred","GET /gists/{gist_id}/comments","GET /gists/{gist_id}/commits","GET /gists/{gist_id}/forks","GET /installation/repositories","GET /issues","GET /licenses","GET /marketplace_listing/plans","GET /marketplace_listing/plans/{plan_id}/accounts","GET /marketplace_listing/stubbed/plans","GET /marketplace_listing/stubbed/plans/{plan_id}/accounts","GET /networks/{owner}/{repo}/events","GET /notifications","GET /organizations","GET /organizations/{org}/dependabot/repository-access","GET /orgs/{org}/actions/cache/usage-by-repository","GET /orgs/{org}/actions/hosted-runners","GET /orgs/{org}/actions/permissions/repositories","GET /orgs/{org}/actions/permissions/self-hosted-runners/repositories","GET /orgs/{org}/actions/runner-groups","GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners","GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories","GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners","GET /orgs/{org}/actions/runners","GET /orgs/{org}/actions/secrets","GET /orgs/{org}/actions/secrets/{secret_name}/repositories","GET /orgs/{org}/actions/variables","GET /orgs/{org}/actions/variables/{name}/repositories","GET /orgs/{org}/attestations/repositories","GET /orgs/{org}/attestations/{subject_digest}","GET /orgs/{org}/blocks","GET /orgs/{org}/campaigns","GET /orgs/{org}/code-scanning/alerts","GET /orgs/{org}/code-security/configurations","GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories","GET /orgs/{org}/codespaces","GET /orgs/{org}/codespaces/secrets","GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories","GET /orgs/{org}/copilot/billing/seats","GET /orgs/{org}/copilot/metrics","GET /orgs/{org}/dependabot/alerts","GET /orgs/{org}/dependabot/secrets","GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories","GET /orgs/{org}/events","GET /orgs/{org}/failed_invitations","GET /orgs/{org}/hooks","GET /orgs/{org}/hooks/{hook_id}/deliveries","GET /orgs/{org}/insights/api/route-stats/{actor_type}/{actor_id}","GET /orgs/{org}/insights/api/subject-stats","GET /orgs/{org}/insights/api/user-stats/{user_id}","GET /orgs/{org}/installations","GET /orgs/{org}/invitations","GET /orgs/{org}/invitations/{invitation_id}/teams","GET /orgs/{org}/issues","GET /orgs/{org}/members","GET /orgs/{org}/members/{username}/codespaces","GET /orgs/{org}/migrations","GET /orgs/{org}/migrations/{migration_id}/repositories","GET /orgs/{org}/organization-roles/{role_id}/teams","GET /orgs/{org}/organization-roles/{role_id}/users","GET /orgs/{org}/outside_collaborators","GET /orgs/{org}/packages","GET /orgs/{org}/packages/{package_type}/{package_name}/versions","GET /orgs/{org}/personal-access-token-requests","GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories","GET /orgs/{org}/personal-access-tokens","GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories","GET /orgs/{org}/private-registries","GET /orgs/{org}/projects","GET /orgs/{org}/projectsV2","GET /orgs/{org}/projectsV2/{project_number}/fields","GET /orgs/{org}/projectsV2/{project_number}/items","GET /orgs/{org}/properties/values","GET /orgs/{org}/public_members","GET /orgs/{org}/repos","GET /orgs/{org}/rulesets","GET /orgs/{org}/rulesets/rule-suites","GET /orgs/{org}/rulesets/{ruleset_id}/history","GET /orgs/{org}/secret-scanning/alerts","GET /orgs/{org}/security-advisories","GET /orgs/{org}/settings/immutable-releases/repositories","GET /orgs/{org}/settings/network-configurations","GET /orgs/{org}/team/{team_slug}/copilot/metrics","GET /orgs/{org}/teams","GET /orgs/{org}/teams/{team_slug}/discussions","GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments","GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions","GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions","GET /orgs/{org}/teams/{team_slug}/invitations","GET /orgs/{org}/teams/{team_slug}/members","GET /orgs/{org}/teams/{team_slug}/projects","GET /orgs/{org}/teams/{team_slug}/repos","GET /orgs/{org}/teams/{team_slug}/teams","GET /projects/{project_id}/collaborators","GET /repos/{owner}/{repo}/actions/artifacts","GET /repos/{owner}/{repo}/actions/caches","GET /repos/{owner}/{repo}/actions/organization-secrets","GET /repos/{owner}/{repo}/actions/organization-variables","GET /repos/{owner}/{repo}/actions/runners","GET /repos/{owner}/{repo}/actions/runs","GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts","GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs","GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs","GET /repos/{owner}/{repo}/actions/secrets","GET /repos/{owner}/{repo}/actions/variables","GET /repos/{owner}/{repo}/actions/workflows","GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs","GET /repos/{owner}/{repo}/activity","GET /repos/{owner}/{repo}/assignees","GET /repos/{owner}/{repo}/attestations/{subject_digest}","GET /repos/{owner}/{repo}/branches","GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations","GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs","GET /repos/{owner}/{repo}/code-scanning/alerts","GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances","GET /repos/{owner}/{repo}/code-scanning/analyses","GET /repos/{owner}/{repo}/codespaces","GET /repos/{owner}/{repo}/codespaces/devcontainers","GET /repos/{owner}/{repo}/codespaces/secrets","GET /repos/{owner}/{repo}/collaborators","GET /repos/{owner}/{repo}/comments","GET /repos/{owner}/{repo}/comments/{comment_id}/reactions","GET /repos/{owner}/{repo}/commits","GET /repos/{owner}/{repo}/commits/{commit_sha}/comments","GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls","GET /repos/{owner}/{repo}/commits/{ref}/check-runs","GET /repos/{owner}/{repo}/commits/{ref}/check-suites","GET /repos/{owner}/{repo}/commits/{ref}/status","GET /repos/{owner}/{repo}/commits/{ref}/statuses","GET /repos/{owner}/{repo}/compare/{basehead}","GET /repos/{owner}/{repo}/compare/{base}...{head}","GET /repos/{owner}/{repo}/contributors","GET /repos/{owner}/{repo}/dependabot/alerts","GET /repos/{owner}/{repo}/dependabot/secrets","GET /repos/{owner}/{repo}/deployments","GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses","GET /repos/{owner}/{repo}/environments","GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies","GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps","GET /repos/{owner}/{repo}/environments/{environment_name}/secrets","GET /repos/{owner}/{repo}/environments/{environment_name}/variables","GET /repos/{owner}/{repo}/events","GET /repos/{owner}/{repo}/forks","GET /repos/{owner}/{repo}/hooks","GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries","GET /repos/{owner}/{repo}/invitations","GET /repos/{owner}/{repo}/issues","GET /repos/{owner}/{repo}/issues/comments","GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions","GET /repos/{owner}/{repo}/issues/events","GET /repos/{owner}/{repo}/issues/{issue_number}/comments","GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by","GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking","GET /repos/{owner}/{repo}/issues/{issue_number}/events","GET /repos/{owner}/{repo}/issues/{issue_number}/labels","GET /repos/{owner}/{repo}/issues/{issue_number}/reactions","GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues","GET /repos/{owner}/{repo}/issues/{issue_number}/timeline","GET /repos/{owner}/{repo}/keys","GET /repos/{owner}/{repo}/labels","GET /repos/{owner}/{repo}/milestones","GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels","GET /repos/{owner}/{repo}/notifications","GET /repos/{owner}/{repo}/pages/builds","GET /repos/{owner}/{repo}/projects","GET /repos/{owner}/{repo}/pulls","GET /repos/{owner}/{repo}/pulls/comments","GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions","GET /repos/{owner}/{repo}/pulls/{pull_number}/comments","GET /repos/{owner}/{repo}/pulls/{pull_number}/commits","GET /repos/{owner}/{repo}/pulls/{pull_number}/files","GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews","GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments","GET /repos/{owner}/{repo}/releases","GET /repos/{owner}/{repo}/releases/{release_id}/assets","GET /repos/{owner}/{repo}/releases/{release_id}/reactions","GET /repos/{owner}/{repo}/rules/branches/{branch}","GET /repos/{owner}/{repo}/rulesets","GET /repos/{owner}/{repo}/rulesets/rule-suites","GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history","GET /repos/{owner}/{repo}/secret-scanning/alerts","GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations","GET /repos/{owner}/{repo}/security-advisories","GET /repos/{owner}/{repo}/stargazers","GET /repos/{owner}/{repo}/subscribers","GET /repos/{owner}/{repo}/tags","GET /repos/{owner}/{repo}/teams","GET /repos/{owner}/{repo}/topics","GET /repositories","GET /search/code","GET /search/commits","GET /search/issues","GET /search/labels","GET /search/repositories","GET /search/topics","GET /search/users","GET /teams/{team_id}/discussions","GET /teams/{team_id}/discussions/{discussion_number}/comments","GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions","GET /teams/{team_id}/discussions/{discussion_number}/reactions","GET /teams/{team_id}/invitations","GET /teams/{team_id}/members","GET /teams/{team_id}/projects","GET /teams/{team_id}/repos","GET /teams/{team_id}/teams","GET /user/blocks","GET /user/codespaces","GET /user/codespaces/secrets","GET /user/emails","GET /user/followers","GET /user/following","GET /user/gpg_keys","GET /user/installations","GET /user/installations/{installation_id}/repositories","GET /user/issues","GET /user/keys","GET /user/marketplace_purchases","GET /user/marketplace_purchases/stubbed","GET /user/memberships/orgs","GET /user/migrations","GET /user/migrations/{migration_id}/repositories","GET /user/orgs","GET /user/packages","GET /user/packages/{package_type}/{package_name}/versions","GET /user/public_emails","GET /user/repos","GET /user/repository_invitations","GET /user/social_accounts","GET /user/ssh_signing_keys","GET /user/starred","GET /user/subscriptions","GET /user/teams","GET /users","GET /users/{username}/attestations/{subject_digest}","GET /users/{username}/events","GET /users/{username}/events/orgs/{org}","GET /users/{username}/events/public","GET /users/{username}/followers","GET /users/{username}/following","GET /users/{username}/gists","GET /users/{username}/gpg_keys","GET /users/{username}/keys","GET /users/{username}/orgs","GET /users/{username}/packages","GET /users/{username}/projects","GET /users/{username}/projectsV2","GET /users/{username}/projectsV2/{project_number}/fields","GET /users/{username}/projectsV2/{project_number}/items","GET /users/{username}/received_events","GET /users/{username}/received_events/public","GET /users/{username}/repos","GET /users/{username}/social_accounts","GET /users/{username}/ssh_signing_keys","GET /users/{username}/starred","GET /users/{username}/subscriptions"];function isPaginatingEndpoint(e){if(typeof e==="string"){return of.includes(e)}else{return false}}function paginateRest(e){return{paginate:Object.assign(paginate.bind(null,e),{iterator:iterator.bind(null,e)})}}paginateRest.VERSION=nf;const af=new Context;const Af=getApiBaseUrl();const cf={baseUrl:Af,request:{agent:getProxyAgent(Af),fetch:getProxyFetch(Af)}};const lf=Octokit.plugin(restEndpointMethods,paginateRest).defaults(cf);function getOctokitOptions(e,t){const r=Object.assign({},t||{});const n=getAuthString(e,r);if(n){r.auth=n}const s=getUserAgentWithOrchestrationId(r.userAgent);if(s){r.userAgent=s}return r}const uf=new Context;function getOctokit(e,t,...r){const n=lf.plugin(...r);return new n(getOctokitOptions(e,t))}var df=__nccwpck_require__(33991);var hf=undefined&&undefined.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,s){function fulfilled(e){try{step(n.next(e))}catch(e){s(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){s(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};const scrubQueryParameters=e=>{const t=new URL(e);t.search="";return t.toString()};function download_artifact_exists(e){return hf(this,void 0,void 0,(function*(){try{yield Gh.access(e);return true}catch(e){if(e.code==="ENOENT"){return false}else{throw e}}}))}function streamExtract(e,t,r){return hf(this,void 0,void 0,(function*(){let n=0;while(n<5){try{return yield streamExtractExternal(e,t,{skipDecompress:r})}catch(e){n++;core_debug(`Failed to download artifact after ${n} retries due to ${e.message}. Retrying in 5 seconds...`);yield new Promise((e=>setTimeout(e,5e3)))}}throw new Error(`Artifact download failed after ${n} retries.`)}))}function streamExtractExternal(e,t){return hf(this,arguments,void 0,(function*(e,t,r={}){const{timeout:n=30*1e3,skipDecompress:s=false}=r;const i=new lib_HttpClient(getUserAgentString());const o=yield i.get(e);if(o.message.statusCode!==200){throw new Error(`Unexpected HTTP response from blob storage: ${o.message.statusCode} ${o.message.statusMessage}`)}const a=o.message.headers["content-type"]||"";const A=a.split(";",1)[0].trim().toLowerCase();const c=new URL(e).pathname.toLowerCase();const h=c.endsWith(".zip");const g=A==="application/zip"||A==="application/x-zip-compressed"||A==="application/zip-compressed"||h;const f=o.message.headers["content-disposition"]||"";let p="artifact";const B=f.match(/filename\*\s*=\s*UTF-8''([^;\r\n]*)/i);const I=f.match(/(?{const timerFn=()=>{const e=new Error(`Blob storage chunk did not respond in ${n}ms`);o.message.destroy(e);r(e)};const i=setTimeout(timerFn,n);const onError=e=>{core_debug(`response.message: Artifact download failed: ${e.message}`);clearTimeout(i);r(e)};const a=l.createHash("sha256").setEncoding("hex");const A=(new nr.PassThrough).on("data",(()=>{i.refresh()})).on("error",onError);o.message.pipe(A);A.pipe(a);const onClose=()=>{clearTimeout(i);if(a){a.end();y=a.read();info(`SHA256 digest of downloaded artifact is ${y}`)}e({sha256Digest:`sha256:${y}`})};if(g&&!s){A.pipe(df.Extract({path:t})).on("close",onClose).on("error",onError)}else{const e=d.join(t,p);const r=u.createWriteStream(e);info(`Downloading raw file (non-zip) to: ${e}`);A.pipe(r).on("close",onClose).on("error",onError)}}))}))}function downloadArtifactPublic(e,t,r,n,s){return hf(this,void 0,void 0,(function*(){const i=yield resolveOrCreateDirectory(s===null||s===void 0?void 0:s.path);const o=getOctokit(n);let a=false;info(`Downloading artifact '${e}' from '${t}/${r}'`);const{headers:A,status:c}=yield o.rest.actions.downloadArtifact({owner:t,repo:r,artifact_id:e,archive_format:"zip",request:{redirect:"manual"}});if(c!==302){throw new Error(`Unable to download artifact. Unexpected status: ${c}`)}const{location:l}=A;if(!l){throw new Error(`Unable to redirect to artifact download url`)}info(`Redirecting to blob download url: ${scrubQueryParameters(l)}`);try{info(`Starting download of artifact to: ${i}`);const e=yield streamExtract(l,i,s===null||s===void 0?void 0:s.skipDecompress);info(`Artifact download completed successfully.`);if(s===null||s===void 0?void 0:s.expectedHash){if((s===null||s===void 0?void 0:s.expectedHash)!==e.sha256Digest){a=true;core_debug(`Computed digest: ${e.sha256Digest}`);core_debug(`Expected digest: ${s.expectedHash}`)}}}catch(e){throw new Error(`Unable to download and extract artifact: ${e.message}`)}return{downloadPath:i,digestMismatch:a}}))}function downloadArtifactInternal(e,t){return hf(this,void 0,void 0,(function*(){const r=yield resolveOrCreateDirectory(t===null||t===void 0?void 0:t.path);const n=internalArtifactTwirpClient();let s=false;const{workflowRunBackendId:i,workflowJobRunBackendId:o}=getBackendIdsFromToken();const a={workflowRunBackendId:i,workflowJobRunBackendId:o,idFilter:Se.create({value:e.toString()})};const{artifacts:A}=yield n.ListArtifacts(a);if(A.length===0){throw new ArtifactNotFoundError(`No artifacts found for ID: ${e}\nAre you trying to download from a different run? Try specifying a github-token with \`actions:read\` scope.`)}if(A.length>1){warning("Multiple artifacts found, defaulting to first.")}const c={workflowRunBackendId:A[0].workflowRunBackendId,workflowJobRunBackendId:A[0].workflowJobRunBackendId,name:A[0].name};const{signedUrl:l}=yield n.GetSignedArtifactURL(c);info(`Redirecting to blob download url: ${scrubQueryParameters(l)}`);try{info(`Starting download of artifact to: ${r}`);const e=yield streamExtract(l,r,t===null||t===void 0?void 0:t.skipDecompress);info(`Artifact download completed successfully.`);if(t===null||t===void 0?void 0:t.expectedHash){if((t===null||t===void 0?void 0:t.expectedHash)!==e.sha256Digest){s=true;core_debug(`Computed digest: ${e.sha256Digest}`);core_debug(`Expected digest: ${t.expectedHash}`)}}}catch(e){throw new Error(`Unable to download and extract artifact: ${e.message}`)}return{downloadPath:r,digestMismatch:s}}))}function resolveOrCreateDirectory(){return hf(this,arguments,void 0,(function*(e=getGitHubWorkspaceDir()){if(!(yield download_artifact_exists(e))){core_debug(`Artifact destination folder does not exist, creating: ${e}`);yield Gh.mkdir(e,{recursive:true})}else{core_debug(`Artifact destination folder already exists: ${e}`)}return e}))}const gf=5;const ff=[400,401,403,404,422];function getRetryOptions(e,t=gf,r=ff){var n;if(t<=0){return[{enabled:false},e.request]}const s={enabled:true};if(r.length>0){s.doNotRetry=r}const i=Object.assign(Object.assign({},e.request),{retries:t});core_debug(`GitHub client configured with: (retries: ${i.retries}, retry-exempt-status-code: ${(n=s.doNotRetry)!==null&&n!==void 0?n:"octokit default: [400, 401, 403, 404, 422]"})`);return[s,i]}const pf="6.0.0";function requestLog(e){e.hook.wrap("request",((t,r)=>{e.log.debug("request",r);const n=Date.now();const s=e.request.endpoint.parse(r);const i=s.url.replace(r.baseUrl,"");return t(r).then((t=>{const r=t.headers["x-github-request-id"];e.log.info(`${s.method} ${i} - ${t.status} with id ${r} in ${Date.now()-n}ms`);return t})).catch((t=>{const r=t.response?.headers["x-github-request-id"]||"UNKNOWN";e.log.error(`${s.method} ${i} - ${t.status} with id ${r} in ${Date.now()-n}ms`);throw t}))}))}requestLog.VERSION=pf;var Ef=__nccwpck_require__(63251);var mf="0.0.0-development";function isRequestError(e){return e.request!==void 0}async function errorRequest(e,t,r,n){if(!isRequestError(r)||!r?.request.request){throw r}if(r.status>=400&&!e.doNotRetry.includes(r.status)){const s=n.request.retries!=null?n.request.retries:e.retries;const i=Math.pow((n.request.retryCount||0)+1,2);throw t.retry.retryRequest(r,s,i)}throw r}async function wrapRequest(e,t,r,n){const s=new Ef;s.on("failed",(function(t,r){const s=~~t.request.request?.retries;const i=~~t.request.request?.retryAfter;n.request.retryCount=r.retryCount+1;if(s>r.retryCount){return i*e.retryAfterBaseValue}}));return s.schedule(requestWithGraphqlErrorHandling.bind(null,e,t,r),n)}async function requestWithGraphqlErrorHandling(e,t,r,n){const s=await r(n);if(s.data&&s.data.errors&&s.data.errors.length>0&&/Something went wrong while executing your query/.test(s.data.errors[0].message)){const r=new RequestError(s.data.errors[0].message,500,{request:n,response:s});return errorRequest(e,t,r,n)}return s}function retry(e,t){const r=Object.assign({enabled:true,retryAfterBaseValue:1e3,doNotRetry:[400,401,403,404,410,422,451],retries:3},t.retry);const n={retry:{retryRequest:(e,t,r)=>{e.request.request=Object.assign({},e.request.request,{retries:t,retryAfter:r});return e}}};if(r.enabled){e.hook.error("request",errorRequest.bind(null,r,n));e.hook.wrap("request",wrapRequest.bind(null,r,n))}return n}retry.VERSION=mf;var Cf=undefined&&undefined.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,s){function fulfilled(e){try{step(n.next(e))}catch(e){s(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){s(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};function getArtifactPublic(e,t,r,n,s){return Cf(this,void 0,void 0,(function*(){var i;const[o,a]=getRetryOptions(cf);const A={log:undefined,userAgent:getUserAgentString(),previews:undefined,retry:o,request:a};const c=getOctokit(s,A,retry,requestLog);const l=yield c.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts{?name}",{owner:r,repo:n,run_id:t,name:e});if(l.status!==200){throw new InvalidResponseError(`Invalid response from GitHub API: ${l.status} (${(i=l===null||l===void 0?void 0:l.headers)===null||i===void 0?void 0:i["x-github-request-id"]})`)}if(l.data.artifacts.length===0){throw new ArtifactNotFoundError(`Artifact not found for name: ${e}\n Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact.\n For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`)}let u=l.data.artifacts[0];if(l.data.artifacts.length>1){u=l.data.artifacts.sort(((e,t)=>t.id-e.id))[0];core_debug(`More than one artifact found for a single name, returning newest (id: ${u.id})`)}return{artifact:{name:u.name,id:u.id,size:u.size_in_bytes,createdAt:u.created_at?new Date(u.created_at):undefined,digest:u.digest}}}))}function getArtifactInternal(e){return Cf(this,void 0,void 0,(function*(){var t;const r=internalArtifactTwirpClient();const{workflowRunBackendId:n,workflowJobRunBackendId:s}=getBackendIdsFromToken();const i={workflowRunBackendId:n,workflowJobRunBackendId:s,nameFilter:Te.create({value:e})};const o=yield r.ListArtifacts(i);if(o.artifacts.length===0){throw new ArtifactNotFoundError(`Artifact not found for name: ${e}\n Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact.\n For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`)}let a=o.artifacts[0];if(o.artifacts.length>1){a=o.artifacts.sort(((e,t)=>Number(t.databaseId)-Number(e.databaseId)))[0];core_debug(`More than one artifact found for a single name, returning newest (id: ${a.databaseId})`)}return{artifact:{name:a.name,id:Number(a.databaseId),size:Number(a.size),createdAt:a.createdAt?ye.toDate(a.createdAt):undefined,digest:(t=a.digest)===null||t===void 0?void 0:t.value}}}))}var Bf=undefined&&undefined.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,s){function fulfilled(e){try{step(n.next(e))}catch(e){s(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){s(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};function deleteArtifactPublic(e,t,r,n,s){return Bf(this,void 0,void 0,(function*(){var i;const[o,a]=getRetryOptions(cf);const A={log:undefined,userAgent:getUserAgentString(),previews:undefined,retry:o,request:a};const c=getOctokit(s,A,retry,requestLog);const l=yield getArtifactPublic(e,t,r,n,s);const u=yield c.rest.actions.deleteArtifact({owner:r,repo:n,artifact_id:l.artifact.id});if(u.status!==204){throw new InvalidResponseError(`Invalid response from GitHub API: ${u.status} (${(i=u===null||u===void 0?void 0:u.headers)===null||i===void 0?void 0:i["x-github-request-id"]})`)}return{id:l.artifact.id}}))}function deleteArtifactInternal(e){return Bf(this,void 0,void 0,(function*(){const t=internalArtifactTwirpClient();const{workflowRunBackendId:r,workflowJobRunBackendId:n}=getBackendIdsFromToken();const s={workflowRunBackendId:r,workflowJobRunBackendId:n,nameFilter:Te.create({value:e})};const i=yield t.ListArtifacts(s);if(i.artifacts.length===0){throw new ArtifactNotFoundError(`Artifact not found for name: ${e}`)}let o=i.artifacts[0];if(i.artifacts.length>1){o=i.artifacts.sort(((e,t)=>Number(t.databaseId)-Number(e.databaseId)))[0];core_debug(`More than one artifact found for a single name, returning newest (id: ${o.databaseId})`)}const a={workflowRunBackendId:o.workflowRunBackendId,workflowJobRunBackendId:o.workflowJobRunBackendId,name:o.name};const A=yield t.DeleteArtifact(a);info(`Artifact '${e}' (ID: ${A.artifactId}) deleted`);return{id:Number(A.artifactId)}}))}var If=undefined&&undefined.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,s){function fulfilled(e){try{step(n.next(e))}catch(e){s(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){s(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};const Qf=getMaxArtifactListCount();const yf=100;const bf=Math.ceil(Qf/yf);function listArtifactsPublic(e,t,r,n){return If(this,arguments,void 0,(function*(e,t,r,n,s=false){info(`Fetching artifact list for workflow run ${e} in repository ${t}/${r}`);let i=[];const[o,a]=getRetryOptions(cf);const A={log:undefined,userAgent:getUserAgentString(),previews:undefined,retry:o,request:a};const c=getOctokit(n,A,retry,requestLog);let l=1;const{data:u}=yield c.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts",{owner:t,repo:r,run_id:e,per_page:yf,page:l});let d=Math.ceil(u.total_count/yf);const h=u.total_count;if(h>Qf){warning(`Workflow run ${e} has ${h} artifacts, exceeding the limit of ${Qf}. Results will be incomplete as only the first ${Qf} artifacts will be returned`);d=bf}for(const e of u.artifacts){i.push({name:e.name,id:e.id,size:e.size_in_bytes,createdAt:e.created_at?new Date(e.created_at):undefined,digest:e.digest})}l++;for(l;l<=d;l++){core_debug(`Fetching page ${l} of artifact list`);const{data:n}=yield c.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts",{owner:t,repo:r,run_id:e,per_page:yf,page:l});for(const e of n.artifacts){i.push({name:e.name,id:e.id,size:e.size_in_bytes,createdAt:e.created_at?new Date(e.created_at):undefined,digest:e.digest})}}if(s){i=filterLatest(i)}info(`Found ${i.length} artifact(s)`);return{artifacts:i}}))}function listArtifactsInternal(){return If(this,arguments,void 0,(function*(e=false){const t=internalArtifactTwirpClient();const{workflowRunBackendId:r,workflowJobRunBackendId:n}=getBackendIdsFromToken();const s={workflowRunBackendId:r,workflowJobRunBackendId:n};const i=yield t.ListArtifacts(s);let o=i.artifacts.map((e=>{var t;return{name:e.name,id:Number(e.databaseId),size:Number(e.size),createdAt:e.createdAt?ye.toDate(e.createdAt):undefined,digest:(t=e.digest)===null||t===void 0?void 0:t.value}}));if(e){o=filterLatest(o)}info(`Found ${o.length} artifact(s)`);return{artifacts:o}}))}function filterLatest(e){e.sort(((e,t)=>t.id-e.id));const t=[];const r=new Set;for(const n of e){if(!r.has(n.name)){t.push(n);r.add(n.name)}}return t}var wf=undefined&&undefined.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,s){function fulfilled(e){try{step(n.next(e))}catch(e){s(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){s(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};var Sf=undefined&&undefined.__rest||function(e,t){var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0)r[n]=e[n];if(e!=null&&typeof Object.getOwnPropertySymbols==="function")for(var s=0,n=Object.getOwnPropertySymbols(e);s!e.endsWith(i.sep)));if(c.length===0){const t=`No files matched pattern: ${e}`;if(s==="error")return o.setFailed(t);if(s==="warn")return o.warning(t);return o.info(t)}const l=new DefaultArtifactClient;const u=process.cwd();const d=[];for(const e of c){const t=i.basename(e);const s=i.relative(u,e)||e;o.info(`Uploading ${t} (${s})`);const a={compressionLevel:n};if(r>0)a.retentionDays=r;const A=await l.uploadArtifact(t,[e],u,a);o.info(` artifact id=${A.id} size=${A.size}`);d.push(t)}o.setOutput("artifact-names",JSON.stringify(d));o.info(`Uploaded ${d.length} artifact(s).`)}run().catch((e=>o.setFailed(e&&e.stack?e.stack:String(e)))); \ No newline at end of file +/* v8 ignore if -- @preserve */var Yg="(?:[a-zA-Z0-9_-]+)";var Vg="\\.";var Jg=new RegExp(`^${Yg}${Vg}${Yg}${Vg}${Yg}$`);var qg=Jg.test.bind(Jg);async function auth(e){const t=qg(e);const r=e.startsWith("v1.")||e.startsWith("ghs_");const n=e.startsWith("ghu_");const s=t?"app":r?"installation":n?"user-to-server":"oauth";return{type:"token",token:e,tokenType:s}}function withAuthorizationPrefix(e){if(e.split(/\./).length===3){return`bearer ${e}`}return`token ${e}`}async function hook(e,t,r,n){const s=t.endpoint.merge(r,n);s.headers.authorization=withAuthorizationPrefix(e);return t(s)}var Wg=function createTokenAuth2(e){if(!e){throw new Error("[@octokit/auth-token] No token passed to createTokenAuth")}if(typeof e!=="string"){throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string")}e=e.replace(/^(token|bearer) +/i,"");return Object.assign(auth.bind(null,e),{hook:hook.bind(null,e)})};const zg="7.0.8";const dist_src_noop=()=>{};const jg=console.warn.bind(console);const Kg=console.error.bind(console);function createLogger(e={}){if(typeof e.debug!=="function"){e.debug=dist_src_noop}if(typeof e.info!=="function"){e.info=dist_src_noop}if(typeof e.warn!=="function"){e.warn=jg}if(typeof e.error!=="function"){e.error=Kg}return e}const Zg=`octokit-core.js/${zg} ${getUserAgent()}`;class Octokit{static VERSION=zg;static defaults(e){const t=class extends(this){constructor(...t){const r=t[0]||{};if(typeof e==="function"){super(e(r));return}super(Object.assign({},e,r,r.userAgent&&e.userAgent?{userAgent:`${r.userAgent} ${e.userAgent}`}:null))}};return t}static plugins=[];static plugin(...e){const t=this.plugins;const r=class extends(this){static plugins=t.concat(e.filter((e=>!t.includes(e))))};return r}constructor(e={}){const t=new eg.Collection;const r={baseUrl:Ug.endpoint.DEFAULTS.baseUrl,headers:{},request:Object.assign({},e.request,{hook:t.bind(null,"request")}),mediaType:{previews:[],format:""}};r.headers["user-agent"]=e.userAgent?`${e.userAgent} ${Zg}`:Zg;if(e.baseUrl){r.baseUrl=e.baseUrl}if(e.previews){r.mediaType.previews=e.previews}if(e.timeZone){r.headers["time-zone"]=e.timeZone}this.request=Ug.defaults(r);this.graphql=withCustomRequest(this.request).defaults(r);this.log=createLogger(e.log);this.hook=t;if(!e.authStrategy){if(!e.auth){this.auth=async()=>({type:"unauthenticated"})}else{const r=Wg(e.auth);t.wrap("request",r.hook);this.auth=r}}else{const{authStrategy:r,...n}=e;const s=r(Object.assign({request:this.request,log:this.log,octokit:this,octokitOptions:n},e.auth));t.wrap("request",s.hook);this.auth=s}const n=this.constructor;for(let t=0;t({async next(){if(!a)return{done:true};try{const e=await s({method:i,url:a,headers:o});const t=normalizePaginatedListResponse(e);a=((t.headers.link||"").match(/<([^<>]+)>;\s*rel="next"/)||[])[1];if(!a&&"total_commits"in t.data){const e=new URL(t.url);const r=e.searchParams;const n=parseInt(r.get("page")||"1",10);const s=parseInt(r.get("per_page")||"250",10);if(n*s{if(s.done){return t}let i=false;function done(){i=true}t=t.concat(n?n(s.value,done):s.value.data);if(i){return t}return gather(e,t,r,n)}))}var sf=Object.assign(paginate,{iterator:iterator});var of=null&&["GET /advisories","GET /app/hook/deliveries","GET /app/installation-requests","GET /app/installations","GET /assignments/{assignment_id}/accepted_assignments","GET /classrooms","GET /classrooms/{classroom_id}/assignments","GET /enterprises/{enterprise}/code-security/configurations","GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories","GET /enterprises/{enterprise}/dependabot/alerts","GET /enterprises/{enterprise}/teams","GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships","GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations","GET /events","GET /gists","GET /gists/public","GET /gists/starred","GET /gists/{gist_id}/comments","GET /gists/{gist_id}/commits","GET /gists/{gist_id}/forks","GET /installation/repositories","GET /issues","GET /licenses","GET /marketplace_listing/plans","GET /marketplace_listing/plans/{plan_id}/accounts","GET /marketplace_listing/stubbed/plans","GET /marketplace_listing/stubbed/plans/{plan_id}/accounts","GET /networks/{owner}/{repo}/events","GET /notifications","GET /organizations","GET /organizations/{org}/dependabot/repository-access","GET /orgs/{org}/actions/cache/usage-by-repository","GET /orgs/{org}/actions/hosted-runners","GET /orgs/{org}/actions/permissions/repositories","GET /orgs/{org}/actions/permissions/self-hosted-runners/repositories","GET /orgs/{org}/actions/runner-groups","GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners","GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories","GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners","GET /orgs/{org}/actions/runners","GET /orgs/{org}/actions/secrets","GET /orgs/{org}/actions/secrets/{secret_name}/repositories","GET /orgs/{org}/actions/variables","GET /orgs/{org}/actions/variables/{name}/repositories","GET /orgs/{org}/attestations/repositories","GET /orgs/{org}/attestations/{subject_digest}","GET /orgs/{org}/blocks","GET /orgs/{org}/campaigns","GET /orgs/{org}/code-scanning/alerts","GET /orgs/{org}/code-security/configurations","GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories","GET /orgs/{org}/codespaces","GET /orgs/{org}/codespaces/secrets","GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories","GET /orgs/{org}/copilot/billing/seats","GET /orgs/{org}/copilot/metrics","GET /orgs/{org}/dependabot/alerts","GET /orgs/{org}/dependabot/secrets","GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories","GET /orgs/{org}/events","GET /orgs/{org}/failed_invitations","GET /orgs/{org}/hooks","GET /orgs/{org}/hooks/{hook_id}/deliveries","GET /orgs/{org}/insights/api/route-stats/{actor_type}/{actor_id}","GET /orgs/{org}/insights/api/subject-stats","GET /orgs/{org}/insights/api/user-stats/{user_id}","GET /orgs/{org}/installations","GET /orgs/{org}/invitations","GET /orgs/{org}/invitations/{invitation_id}/teams","GET /orgs/{org}/issues","GET /orgs/{org}/members","GET /orgs/{org}/members/{username}/codespaces","GET /orgs/{org}/migrations","GET /orgs/{org}/migrations/{migration_id}/repositories","GET /orgs/{org}/organization-roles/{role_id}/teams","GET /orgs/{org}/organization-roles/{role_id}/users","GET /orgs/{org}/outside_collaborators","GET /orgs/{org}/packages","GET /orgs/{org}/packages/{package_type}/{package_name}/versions","GET /orgs/{org}/personal-access-token-requests","GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories","GET /orgs/{org}/personal-access-tokens","GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories","GET /orgs/{org}/private-registries","GET /orgs/{org}/projects","GET /orgs/{org}/projectsV2","GET /orgs/{org}/projectsV2/{project_number}/fields","GET /orgs/{org}/projectsV2/{project_number}/items","GET /orgs/{org}/properties/values","GET /orgs/{org}/public_members","GET /orgs/{org}/repos","GET /orgs/{org}/rulesets","GET /orgs/{org}/rulesets/rule-suites","GET /orgs/{org}/rulesets/{ruleset_id}/history","GET /orgs/{org}/secret-scanning/alerts","GET /orgs/{org}/security-advisories","GET /orgs/{org}/settings/immutable-releases/repositories","GET /orgs/{org}/settings/network-configurations","GET /orgs/{org}/team/{team_slug}/copilot/metrics","GET /orgs/{org}/teams","GET /orgs/{org}/teams/{team_slug}/discussions","GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments","GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions","GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions","GET /orgs/{org}/teams/{team_slug}/invitations","GET /orgs/{org}/teams/{team_slug}/members","GET /orgs/{org}/teams/{team_slug}/projects","GET /orgs/{org}/teams/{team_slug}/repos","GET /orgs/{org}/teams/{team_slug}/teams","GET /projects/{project_id}/collaborators","GET /repos/{owner}/{repo}/actions/artifacts","GET /repos/{owner}/{repo}/actions/caches","GET /repos/{owner}/{repo}/actions/organization-secrets","GET /repos/{owner}/{repo}/actions/organization-variables","GET /repos/{owner}/{repo}/actions/runners","GET /repos/{owner}/{repo}/actions/runs","GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts","GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs","GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs","GET /repos/{owner}/{repo}/actions/secrets","GET /repos/{owner}/{repo}/actions/variables","GET /repos/{owner}/{repo}/actions/workflows","GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs","GET /repos/{owner}/{repo}/activity","GET /repos/{owner}/{repo}/assignees","GET /repos/{owner}/{repo}/attestations/{subject_digest}","GET /repos/{owner}/{repo}/branches","GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations","GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs","GET /repos/{owner}/{repo}/code-scanning/alerts","GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances","GET /repos/{owner}/{repo}/code-scanning/analyses","GET /repos/{owner}/{repo}/codespaces","GET /repos/{owner}/{repo}/codespaces/devcontainers","GET /repos/{owner}/{repo}/codespaces/secrets","GET /repos/{owner}/{repo}/collaborators","GET /repos/{owner}/{repo}/comments","GET /repos/{owner}/{repo}/comments/{comment_id}/reactions","GET /repos/{owner}/{repo}/commits","GET /repos/{owner}/{repo}/commits/{commit_sha}/comments","GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls","GET /repos/{owner}/{repo}/commits/{ref}/check-runs","GET /repos/{owner}/{repo}/commits/{ref}/check-suites","GET /repos/{owner}/{repo}/commits/{ref}/status","GET /repos/{owner}/{repo}/commits/{ref}/statuses","GET /repos/{owner}/{repo}/compare/{basehead}","GET /repos/{owner}/{repo}/compare/{base}...{head}","GET /repos/{owner}/{repo}/contributors","GET /repos/{owner}/{repo}/dependabot/alerts","GET /repos/{owner}/{repo}/dependabot/secrets","GET /repos/{owner}/{repo}/deployments","GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses","GET /repos/{owner}/{repo}/environments","GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies","GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps","GET /repos/{owner}/{repo}/environments/{environment_name}/secrets","GET /repos/{owner}/{repo}/environments/{environment_name}/variables","GET /repos/{owner}/{repo}/events","GET /repos/{owner}/{repo}/forks","GET /repos/{owner}/{repo}/hooks","GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries","GET /repos/{owner}/{repo}/invitations","GET /repos/{owner}/{repo}/issues","GET /repos/{owner}/{repo}/issues/comments","GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions","GET /repos/{owner}/{repo}/issues/events","GET /repos/{owner}/{repo}/issues/{issue_number}/comments","GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by","GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking","GET /repos/{owner}/{repo}/issues/{issue_number}/events","GET /repos/{owner}/{repo}/issues/{issue_number}/labels","GET /repos/{owner}/{repo}/issues/{issue_number}/reactions","GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues","GET /repos/{owner}/{repo}/issues/{issue_number}/timeline","GET /repos/{owner}/{repo}/keys","GET /repos/{owner}/{repo}/labels","GET /repos/{owner}/{repo}/milestones","GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels","GET /repos/{owner}/{repo}/notifications","GET /repos/{owner}/{repo}/pages/builds","GET /repos/{owner}/{repo}/projects","GET /repos/{owner}/{repo}/pulls","GET /repos/{owner}/{repo}/pulls/comments","GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions","GET /repos/{owner}/{repo}/pulls/{pull_number}/comments","GET /repos/{owner}/{repo}/pulls/{pull_number}/commits","GET /repos/{owner}/{repo}/pulls/{pull_number}/files","GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews","GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments","GET /repos/{owner}/{repo}/releases","GET /repos/{owner}/{repo}/releases/{release_id}/assets","GET /repos/{owner}/{repo}/releases/{release_id}/reactions","GET /repos/{owner}/{repo}/rules/branches/{branch}","GET /repos/{owner}/{repo}/rulesets","GET /repos/{owner}/{repo}/rulesets/rule-suites","GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history","GET /repos/{owner}/{repo}/secret-scanning/alerts","GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations","GET /repos/{owner}/{repo}/security-advisories","GET /repos/{owner}/{repo}/stargazers","GET /repos/{owner}/{repo}/subscribers","GET /repos/{owner}/{repo}/tags","GET /repos/{owner}/{repo}/teams","GET /repos/{owner}/{repo}/topics","GET /repositories","GET /search/code","GET /search/commits","GET /search/issues","GET /search/labels","GET /search/repositories","GET /search/topics","GET /search/users","GET /teams/{team_id}/discussions","GET /teams/{team_id}/discussions/{discussion_number}/comments","GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions","GET /teams/{team_id}/discussions/{discussion_number}/reactions","GET /teams/{team_id}/invitations","GET /teams/{team_id}/members","GET /teams/{team_id}/projects","GET /teams/{team_id}/repos","GET /teams/{team_id}/teams","GET /user/blocks","GET /user/codespaces","GET /user/codespaces/secrets","GET /user/emails","GET /user/followers","GET /user/following","GET /user/gpg_keys","GET /user/installations","GET /user/installations/{installation_id}/repositories","GET /user/issues","GET /user/keys","GET /user/marketplace_purchases","GET /user/marketplace_purchases/stubbed","GET /user/memberships/orgs","GET /user/migrations","GET /user/migrations/{migration_id}/repositories","GET /user/orgs","GET /user/packages","GET /user/packages/{package_type}/{package_name}/versions","GET /user/public_emails","GET /user/repos","GET /user/repository_invitations","GET /user/social_accounts","GET /user/ssh_signing_keys","GET /user/starred","GET /user/subscriptions","GET /user/teams","GET /users","GET /users/{username}/attestations/{subject_digest}","GET /users/{username}/events","GET /users/{username}/events/orgs/{org}","GET /users/{username}/events/public","GET /users/{username}/followers","GET /users/{username}/following","GET /users/{username}/gists","GET /users/{username}/gpg_keys","GET /users/{username}/keys","GET /users/{username}/orgs","GET /users/{username}/packages","GET /users/{username}/projects","GET /users/{username}/projectsV2","GET /users/{username}/projectsV2/{project_number}/fields","GET /users/{username}/projectsV2/{project_number}/items","GET /users/{username}/received_events","GET /users/{username}/received_events/public","GET /users/{username}/repos","GET /users/{username}/social_accounts","GET /users/{username}/ssh_signing_keys","GET /users/{username}/starred","GET /users/{username}/subscriptions"];function isPaginatingEndpoint(e){if(typeof e==="string"){return of.includes(e)}else{return false}}function paginateRest(e){return{paginate:Object.assign(paginate.bind(null,e),{iterator:iterator.bind(null,e)})}}paginateRest.VERSION=nf;const af=new Context;const Af=getApiBaseUrl();const cf={baseUrl:Af,request:{agent:getProxyAgent(Af),fetch:getProxyFetch(Af)}};const lf=Octokit.plugin(restEndpointMethods,paginateRest).defaults(cf);function getOctokitOptions(e,t){const r=Object.assign({},t||{});const n=getAuthString(e,r);if(n){r.auth=n}const s=getUserAgentWithOrchestrationId(r.userAgent);if(s){r.userAgent=s}return r}const uf=new Context;function getOctokit(e,t,...r){const n=lf.plugin(...r);return new n(getOctokitOptions(e,t))}var df=__nccwpck_require__(33991);var hf=undefined&&undefined.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,s){function fulfilled(e){try{step(n.next(e))}catch(e){s(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){s(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};const scrubQueryParameters=e=>{const t=new URL(e);t.search="";return t.toString()};function download_artifact_exists(e){return hf(this,void 0,void 0,(function*(){try{yield Gh.access(e);return true}catch(e){if(e.code==="ENOENT"){return false}else{throw e}}}))}function streamExtract(e,t,r){return hf(this,void 0,void 0,(function*(){let n=0;while(n<5){try{return yield streamExtractExternal(e,t,{skipDecompress:r})}catch(e){n++;core_debug(`Failed to download artifact after ${n} retries due to ${e.message}. Retrying in 5 seconds...`);yield new Promise((e=>setTimeout(e,5e3)))}}throw new Error(`Artifact download failed after ${n} retries.`)}))}function streamExtractExternal(e,t){return hf(this,arguments,void 0,(function*(e,t,r={}){const{timeout:n=30*1e3,skipDecompress:s=false}=r;const i=new lib_HttpClient(getUserAgentString());const o=yield i.get(e);if(o.message.statusCode!==200){throw new Error(`Unexpected HTTP response from blob storage: ${o.message.statusCode} ${o.message.statusMessage}`)}const a=o.message.headers["content-type"]||"";const A=a.split(";",1)[0].trim().toLowerCase();const c=new URL(e).pathname.toLowerCase();const h=c.endsWith(".zip");const g=A==="application/zip"||A==="application/x-zip-compressed"||A==="application/zip-compressed"||h;const f=o.message.headers["content-disposition"]||"";let p="artifact";const B=f.match(/filename\*\s*=\s*UTF-8''([^;\r\n]*)/i);const I=f.match(/(?{const timerFn=()=>{const e=new Error(`Blob storage chunk did not respond in ${n}ms`);o.message.destroy(e);r(e)};const i=setTimeout(timerFn,n);const onError=e=>{core_debug(`response.message: Artifact download failed: ${e.message}`);clearTimeout(i);r(e)};const a=l.createHash("sha256").setEncoding("hex");const A=(new nr.PassThrough).on("data",(()=>{i.refresh()})).on("error",onError);o.message.pipe(A);A.pipe(a);const onClose=()=>{clearTimeout(i);if(a){a.end();y=a.read();info(`SHA256 digest of downloaded artifact is ${y}`)}e({sha256Digest:`sha256:${y}`})};if(g&&!s){A.pipe(df.Extract({path:t})).on("close",onClose).on("error",onError)}else{const e=d.join(t,p);const r=u.createWriteStream(e);info(`Downloading raw file (non-zip) to: ${e}`);A.pipe(r).on("close",onClose).on("error",onError)}}))}))}function downloadArtifactPublic(e,t,r,n,s){return hf(this,void 0,void 0,(function*(){const i=yield resolveOrCreateDirectory(s===null||s===void 0?void 0:s.path);const o=getOctokit(n);let a=false;info(`Downloading artifact '${e}' from '${t}/${r}'`);const{headers:A,status:c}=yield o.rest.actions.downloadArtifact({owner:t,repo:r,artifact_id:e,archive_format:"zip",request:{redirect:"manual"}});if(c!==302){throw new Error(`Unable to download artifact. Unexpected status: ${c}`)}const{location:l}=A;if(!l){throw new Error(`Unable to redirect to artifact download url`)}info(`Redirecting to blob download url: ${scrubQueryParameters(l)}`);try{info(`Starting download of artifact to: ${i}`);const e=yield streamExtract(l,i,s===null||s===void 0?void 0:s.skipDecompress);info(`Artifact download completed successfully.`);if(s===null||s===void 0?void 0:s.expectedHash){if((s===null||s===void 0?void 0:s.expectedHash)!==e.sha256Digest){a=true;core_debug(`Computed digest: ${e.sha256Digest}`);core_debug(`Expected digest: ${s.expectedHash}`)}}}catch(e){throw new Error(`Unable to download and extract artifact: ${e.message}`)}return{downloadPath:i,digestMismatch:a}}))}function downloadArtifactInternal(e,t){return hf(this,void 0,void 0,(function*(){const r=yield resolveOrCreateDirectory(t===null||t===void 0?void 0:t.path);const n=internalArtifactTwirpClient();let s=false;const{workflowRunBackendId:i,workflowJobRunBackendId:o}=getBackendIdsFromToken();const a={workflowRunBackendId:i,workflowJobRunBackendId:o,idFilter:Se.create({value:e.toString()})};const{artifacts:A}=yield n.ListArtifacts(a);if(A.length===0){throw new ArtifactNotFoundError(`No artifacts found for ID: ${e}\nAre you trying to download from a different run? Try specifying a github-token with \`actions:read\` scope.`)}if(A.length>1){warning("Multiple artifacts found, defaulting to first.")}const c={workflowRunBackendId:A[0].workflowRunBackendId,workflowJobRunBackendId:A[0].workflowJobRunBackendId,name:A[0].name};const{signedUrl:l}=yield n.GetSignedArtifactURL(c);info(`Redirecting to blob download url: ${scrubQueryParameters(l)}`);try{info(`Starting download of artifact to: ${r}`);const e=yield streamExtract(l,r,t===null||t===void 0?void 0:t.skipDecompress);info(`Artifact download completed successfully.`);if(t===null||t===void 0?void 0:t.expectedHash){if((t===null||t===void 0?void 0:t.expectedHash)!==e.sha256Digest){s=true;core_debug(`Computed digest: ${e.sha256Digest}`);core_debug(`Expected digest: ${t.expectedHash}`)}}}catch(e){throw new Error(`Unable to download and extract artifact: ${e.message}`)}return{downloadPath:r,digestMismatch:s}}))}function resolveOrCreateDirectory(){return hf(this,arguments,void 0,(function*(e=getGitHubWorkspaceDir()){if(!(yield download_artifact_exists(e))){core_debug(`Artifact destination folder does not exist, creating: ${e}`);yield Gh.mkdir(e,{recursive:true})}else{core_debug(`Artifact destination folder already exists: ${e}`)}return e}))}const gf=5;const ff=[400,401,403,404,422];function getRetryOptions(e,t=gf,r=ff){var n;if(t<=0){return[{enabled:false},e.request]}const s={enabled:true};if(r.length>0){s.doNotRetry=r}const i=Object.assign(Object.assign({},e.request),{retries:t});core_debug(`GitHub client configured with: (retries: ${i.retries}, retry-exempt-status-code: ${(n=s.doNotRetry)!==null&&n!==void 0?n:"octokit default: [400, 401, 403, 404, 422]"})`);return[s,i]}const pf="6.0.0";function requestLog(e){e.hook.wrap("request",((t,r)=>{e.log.debug("request",r);const n=Date.now();const s=e.request.endpoint.parse(r);const i=s.url.replace(r.baseUrl,"");return t(r).then((t=>{const r=t.headers["x-github-request-id"];e.log.info(`${s.method} ${i} - ${t.status} with id ${r} in ${Date.now()-n}ms`);return t})).catch((t=>{const r=t.response?.headers["x-github-request-id"]||"UNKNOWN";e.log.error(`${s.method} ${i} - ${t.status} with id ${r} in ${Date.now()-n}ms`);throw t}))}))}requestLog.VERSION=pf;var Ef=__nccwpck_require__(63251);var mf="0.0.0-development";function isRequestError(e){return e.request!==void 0}async function errorRequest(e,t,r,n){if(!isRequestError(r)||!r?.request.request){throw r}if(r.status>=400&&!e.doNotRetry.includes(r.status)){const s=n.request.retries!=null?n.request.retries:e.retries;const i=Math.pow((n.request.retryCount||0)+1,2);throw t.retry.retryRequest(r,s,i)}throw r}async function wrapRequest(e,t,r,n){const s=new Ef;s.on("failed",(function(t,r){const s=~~t.request.request?.retries;const i=~~t.request.request?.retryAfter;n.request.retryCount=r.retryCount+1;if(s>r.retryCount){return i*e.retryAfterBaseValue}}));return s.schedule(requestWithGraphqlErrorHandling.bind(null,e,t,r),n)}async function requestWithGraphqlErrorHandling(e,t,r,n){const s=await r(n);if(s.data&&s.data.errors&&s.data.errors.length>0&&/Something went wrong while executing your query/.test(s.data.errors[0].message)){const r=new RequestError(s.data.errors[0].message,500,{request:n,response:s});return errorRequest(e,t,r,n)}return s}function retry(e,t){const r=Object.assign({enabled:true,retryAfterBaseValue:1e3,doNotRetry:[400,401,403,404,410,422,451],retries:3},t.retry);const n={retry:{retryRequest:(e,t,r)=>{e.request.request=Object.assign({},e.request.request,{retries:t,retryAfter:r});return e}}};if(r.enabled){e.hook.error("request",errorRequest.bind(null,r,n));e.hook.wrap("request",wrapRequest.bind(null,r,n))}return n}retry.VERSION=mf;var Cf=undefined&&undefined.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,s){function fulfilled(e){try{step(n.next(e))}catch(e){s(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){s(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};function getArtifactPublic(e,t,r,n,s){return Cf(this,void 0,void 0,(function*(){var i;const[o,a]=getRetryOptions(cf);const A={log:undefined,userAgent:getUserAgentString(),previews:undefined,retry:o,request:a};const c=getOctokit(s,A,retry,requestLog);const l=yield c.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts{?name}",{owner:r,repo:n,run_id:t,name:e});if(l.status!==200){throw new InvalidResponseError(`Invalid response from GitHub API: ${l.status} (${(i=l===null||l===void 0?void 0:l.headers)===null||i===void 0?void 0:i["x-github-request-id"]})`)}if(l.data.artifacts.length===0){throw new ArtifactNotFoundError(`Artifact not found for name: ${e}\n Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact.\n For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`)}let u=l.data.artifacts[0];if(l.data.artifacts.length>1){u=l.data.artifacts.sort(((e,t)=>t.id-e.id))[0];core_debug(`More than one artifact found for a single name, returning newest (id: ${u.id})`)}return{artifact:{name:u.name,id:u.id,size:u.size_in_bytes,createdAt:u.created_at?new Date(u.created_at):undefined,digest:u.digest}}}))}function getArtifactInternal(e){return Cf(this,void 0,void 0,(function*(){var t;const r=internalArtifactTwirpClient();const{workflowRunBackendId:n,workflowJobRunBackendId:s}=getBackendIdsFromToken();const i={workflowRunBackendId:n,workflowJobRunBackendId:s,nameFilter:Te.create({value:e})};const o=yield r.ListArtifacts(i);if(o.artifacts.length===0){throw new ArtifactNotFoundError(`Artifact not found for name: ${e}\n Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact.\n For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`)}let a=o.artifacts[0];if(o.artifacts.length>1){a=o.artifacts.sort(((e,t)=>Number(t.databaseId)-Number(e.databaseId)))[0];core_debug(`More than one artifact found for a single name, returning newest (id: ${a.databaseId})`)}return{artifact:{name:a.name,id:Number(a.databaseId),size:Number(a.size),createdAt:a.createdAt?ye.toDate(a.createdAt):undefined,digest:(t=a.digest)===null||t===void 0?void 0:t.value}}}))}var Bf=undefined&&undefined.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,s){function fulfilled(e){try{step(n.next(e))}catch(e){s(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){s(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};function deleteArtifactPublic(e,t,r,n,s){return Bf(this,void 0,void 0,(function*(){var i;const[o,a]=getRetryOptions(cf);const A={log:undefined,userAgent:getUserAgentString(),previews:undefined,retry:o,request:a};const c=getOctokit(s,A,retry,requestLog);const l=yield getArtifactPublic(e,t,r,n,s);const u=yield c.rest.actions.deleteArtifact({owner:r,repo:n,artifact_id:l.artifact.id});if(u.status!==204){throw new InvalidResponseError(`Invalid response from GitHub API: ${u.status} (${(i=u===null||u===void 0?void 0:u.headers)===null||i===void 0?void 0:i["x-github-request-id"]})`)}return{id:l.artifact.id}}))}function deleteArtifactInternal(e){return Bf(this,void 0,void 0,(function*(){const t=internalArtifactTwirpClient();const{workflowRunBackendId:r,workflowJobRunBackendId:n}=getBackendIdsFromToken();const s={workflowRunBackendId:r,workflowJobRunBackendId:n,nameFilter:Te.create({value:e})};const i=yield t.ListArtifacts(s);if(i.artifacts.length===0){throw new ArtifactNotFoundError(`Artifact not found for name: ${e}`)}let o=i.artifacts[0];if(i.artifacts.length>1){o=i.artifacts.sort(((e,t)=>Number(t.databaseId)-Number(e.databaseId)))[0];core_debug(`More than one artifact found for a single name, returning newest (id: ${o.databaseId})`)}const a={workflowRunBackendId:o.workflowRunBackendId,workflowJobRunBackendId:o.workflowJobRunBackendId,name:o.name};const A=yield t.DeleteArtifact(a);info(`Artifact '${e}' (ID: ${A.artifactId}) deleted`);return{id:Number(A.artifactId)}}))}var If=undefined&&undefined.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,s){function fulfilled(e){try{step(n.next(e))}catch(e){s(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){s(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};const Qf=getMaxArtifactListCount();const yf=100;const bf=Math.ceil(Qf/yf);function listArtifactsPublic(e,t,r,n){return If(this,arguments,void 0,(function*(e,t,r,n,s=false){info(`Fetching artifact list for workflow run ${e} in repository ${t}/${r}`);let i=[];const[o,a]=getRetryOptions(cf);const A={log:undefined,userAgent:getUserAgentString(),previews:undefined,retry:o,request:a};const c=getOctokit(n,A,retry,requestLog);let l=1;const{data:u}=yield c.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts",{owner:t,repo:r,run_id:e,per_page:yf,page:l});let d=Math.ceil(u.total_count/yf);const h=u.total_count;if(h>Qf){warning(`Workflow run ${e} has ${h} artifacts, exceeding the limit of ${Qf}. Results will be incomplete as only the first ${Qf} artifacts will be returned`);d=bf}for(const e of u.artifacts){i.push({name:e.name,id:e.id,size:e.size_in_bytes,createdAt:e.created_at?new Date(e.created_at):undefined,digest:e.digest})}l++;for(l;l<=d;l++){core_debug(`Fetching page ${l} of artifact list`);const{data:n}=yield c.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts",{owner:t,repo:r,run_id:e,per_page:yf,page:l});for(const e of n.artifacts){i.push({name:e.name,id:e.id,size:e.size_in_bytes,createdAt:e.created_at?new Date(e.created_at):undefined,digest:e.digest})}}if(s){i=filterLatest(i)}info(`Found ${i.length} artifact(s)`);return{artifacts:i}}))}function listArtifactsInternal(){return If(this,arguments,void 0,(function*(e=false){const t=internalArtifactTwirpClient();const{workflowRunBackendId:r,workflowJobRunBackendId:n}=getBackendIdsFromToken();const s={workflowRunBackendId:r,workflowJobRunBackendId:n};const i=yield t.ListArtifacts(s);let o=i.artifacts.map((e=>{var t;return{name:e.name,id:Number(e.databaseId),size:Number(e.size),createdAt:e.createdAt?ye.toDate(e.createdAt):undefined,digest:(t=e.digest)===null||t===void 0?void 0:t.value}}));if(e){o=filterLatest(o)}info(`Found ${o.length} artifact(s)`);return{artifacts:o}}))}function filterLatest(e){e.sort(((e,t)=>t.id-e.id));const t=[];const r=new Set;for(const n of e){if(!r.has(n.name)){t.push(n);r.add(n.name)}}return t}var wf=undefined&&undefined.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,s){function fulfilled(e){try{step(n.next(e))}catch(e){s(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){s(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};var Sf=undefined&&undefined.__rest||function(e,t){var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0)r[n]=e[n];if(e!=null&&typeof Object.getOwnPropertySymbols==="function")for(var s=0,n=Object.getOwnPropertySymbols(e);s!e.endsWith(i.sep)));if(l.length===0){const t=`No files matched pattern: ${e}`;if(A==="error")return o.setFailed(t);if(A==="warn")return o.warning(t);return o.info(t)}const u=new DefaultArtifactClient;const d=process.cwd();const h=[];for(const e of l){const t=i.basename(e);const a=i.relative(d,e)||e;o.info(`Uploading ${t} (${a})`);const A=s?{compressionLevel:n}:{skipArchive:true};if(r>0)A.retentionDays=r;const c=await u.uploadArtifact(t,[e],d,A);o.info(` artifact id=${c.id} size=${c.size}`);h.push(t)}o.setOutput("artifact-names",JSON.stringify(h));o.info(`Uploaded ${h.length} artifact(s).`)}run().catch((e=>o.setFailed(e&&e.stack?e.stack:String(e)))); \ No newline at end of file diff --git a/.github/actions/upload-each/src/index.js b/.github/actions/upload-each/src/index.js index cafa25b703..9295b4248c 100644 --- a/.github/actions/upload-each/src/index.js +++ b/.github/actions/upload-each/src/index.js @@ -11,6 +11,7 @@ async function run() { core.getInput('compression-level') || '6', 10, ) + const archive = core.getInput('archive') !== 'false' const ifNoFilesFound = ( core.getInput('if-no-files-found') || 'warn' ).toLowerCase() @@ -33,7 +34,7 @@ async function run() { const name = path.basename(file) const rel = path.relative(cwd, file) || file core.info(`Uploading ${name} (${rel})`) - const opts = { compressionLevel } + const opts = archive ? { compressionLevel } : { skipArchive: true } if (retentionDays > 0) opts.retentionDays = retentionDays const result = await client.uploadArtifact(name, [file], cwd, opts) core.info(` artifact id=${result.id} size=${result.size}`) diff --git a/.github/actions/upload-each/test/index.test.cjs b/.github/actions/upload-each/test/index.test.cjs index 9d29b0420b..df4f4ccea4 100644 --- a/.github/actions/upload-each/test/index.test.cjs +++ b/.github/actions/upload-each/test/index.test.cjs @@ -98,6 +98,17 @@ test('uses repository retention and compression defaults', async () => { ]) }) +test('uploads each file unarchived when archive is false', async () => { + const file = path.resolve('one.s9pk') + const { uploads } = await runAction( + { pattern: '*.s9pk', archive: 'false', 'compression-level': '0' }, + [file], + ) + assert.deepEqual(uploads, [ + ['one.s9pk', [file], process.cwd(), { skipArchive: true }], + ]) +}) + for (const mode of ['warn', 'error', 'ignore']) { test(`handles no files in ${mode} mode without uploading`, async () => { const { uploads, messages, outcome } = await runAction( diff --git a/.github/actions/use-compiled-artifacts/action.yml b/.github/actions/use-compiled-artifacts/action.yml new file mode 100644 index 0000000000..f28072698c --- /dev/null +++ b/.github/actions/use-compiled-artifacts/action.yml @@ -0,0 +1,45 @@ +name: Use compiled artifacts +description: >- + Unpacks a build-products.yaml run's compiled-.tar.gz into the checkout + and marks it current, so make uses it rather than recompiling. + Requires `actions: read`. +inputs: + arch: + description: Architecture whose tarball to unpack + required: true + run-id: + description: Run holding the tarball + required: true +runs: + using: composite + steps: + - uses: actions/download-artifact@v8 + with: + name: compiled-${{ inputs.arch }}.tar.gz + run-id: ${{ inputs.run-id }} + github-token: ${{ github.token }} + + - shell: bash + env: + TARBALL: compiled-${{ inputs.arch }}.tar.gz + run: | + set -euo pipefail + tar -xzvf "$TARBALL" + mkdir -p node_modules + mkdir -p projects/start-os/web/dist/raw + mkdir -p projects/start-tunnel/web/dist/raw + mkdir -p shared-libs/crates/start-core/bindings + mkdir -p shared-libs/ts-modules/start-core/lib/osBindings + mkdir -p projects/start-os/container-runtime/node_modules + mkdir -p projects/start-os/container-runtime/dist + mkdir -p projects/start-os/container-runtime/dist/node_modules + mkdir -p projects/start-sdk/dist + mkdir -p shared-libs/ts-modules/start-core/dist + mkdir -p shared-libs/crates/patch-db/client/node_modules + mkdir -p shared-libs/crates/patch-db/client/dist + mkdir -p .angular + mkdir -p projects/start-os/web/dist/raw/ui + mkdir -p projects/start-os/web/dist/raw/setup-wizard + mkdir -p projects/start-os/web/dist/static/ui + mkdir -p projects/start-os/web/dist/static/setup-wizard + make -t "$TARBALL" diff --git a/.github/scripts/changed-products.mjs b/.github/scripts/changed-products.mjs index bcfbfdb3f1..5aa7fe671c 100644 --- a/.github/scripts/changed-products.mjs +++ b/.github/scripts/changed-products.mjs @@ -118,6 +118,8 @@ export const OS_IMAGE_PATHS = [ 'projects/start-os/changelog/**', 'projects/start-os/*.service', 'projects/start-os/*.slice', + 'projects/start-os/container-runtime/*.sh', + 'projects/start-os/container-runtime/*.service', 'scripts/changelog*.mjs', 'shared-libs/crates/start-core/locales/release-notes.json', '.prettierrc.json', diff --git a/.github/workflows/apt-publish-alpha.yml b/.github/workflows/apt-publish-alpha.yml index a7a7d958db..b11bf71a77 100644 --- a/.github/workflows/apt-publish-alpha.yml +++ b/.github/workflows/apt-publish-alpha.yml @@ -60,10 +60,9 @@ jobs: products=(start-cli start-tunnel start-registry) arches=(x86_64 aarch64 riscv64) declare -A chosen=() + product_glob=$(IFS='|'; printf '%s' "${products[*]}") candidate_ids=$( - for product in "${products[@]}"; do - ./scripts/gha-artifact-run-ids.sh "$GITHUB_REPOSITORY" "${product}_${arches[0]}.deb" master || exit 1 - done | sort -nu + ./scripts/gha-artifact-run-ids.sh "$GITHUB_REPOSITORY" "@($product_glob)-*_${arches[0]}.deb" master | sort -nu ) run_metadata=$( for run_id in $candidate_ids; do @@ -85,7 +84,11 @@ jobs: [ -z "${chosen[$product]:-}" ] || continue complete=1 for arch in "${arches[@]}"; do - grep -qx "${product}_${arch}.deb" <<< "$names" || complete=0 + has_deb=0 + while read -r name; do + [[ $name != ${product}-*_${arch}.deb ]] || has_deb=1 + done <<< "$names" + [ "$has_deb" = 1 ] || complete=0 done [ "$complete" = 0 ] || chosen[$product]=$run_id done @@ -98,7 +101,7 @@ jobs: echo "::warning::$product has no complete master build left; the suite keeps whatever version it already holds." continue fi - gh run download -R "$GITHUB_REPOSITORY" "$run_id" -p "${product}_*.deb" -D debs + ./scripts/gha-artifact-download.sh "$GITHUB_REPOSITORY" "$run_id" "${product}-*.deb" debs echo "$product: collected from run $run_id ($(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id" --jq .head_sha))" collected=1 done diff --git a/.github/workflows/build-products.yaml b/.github/workflows/build-products.yaml index 2d58b5444b..ba9896ac47 100644 --- a/.github/workflows/build-products.yaml +++ b/.github/workflows/build-products.yaml @@ -197,12 +197,13 @@ jobs: - name: Package StartOS if: needs.changes.outputs.start-os == 'true' - run: make compiled-${{ matrix.arch }}.tar + run: make compiled-${{ matrix.arch }}.tar.gz + # Uploaded as-is: a zipped artifact drops the binaries' execute bits. - if: needs.changes.outputs.start-os == 'true' uses: actions/upload-artifact@v7 with: - name: compiled-${{ matrix.arch }}.tar - path: compiled-${{ matrix.arch }}.tar + path: compiled-${{ matrix.arch }}.tar.gz + archive: false retention-days: 1 - name: Package start-cli @@ -211,8 +212,8 @@ jobs: - if: needs.changes.outputs.start-cli == 'true' uses: actions/upload-artifact@v7 with: - name: start-cli_${{ matrix.arch }}.deb path: results/start-cli-*_${{ matrix.arch }}.deb + archive: false retention-days: 14 - if: needs.changes.outputs.start-cli == 'true' uses: actions/upload-artifact@v7 @@ -227,8 +228,8 @@ jobs: - if: needs.changes.outputs.start-registry == 'true' uses: actions/upload-artifact@v7 with: - name: start-registry_${{ matrix.arch }}.deb path: results/start-registry-*_${{ matrix.arch }}.deb + archive: false retention-days: 14 - name: Package start-tunnel @@ -237,8 +238,8 @@ jobs: - if: needs.changes.outputs.start-tunnel == 'true' uses: actions/upload-artifact@v7 with: - name: start-tunnel_${{ matrix.arch }}.deb path: results/start-tunnel-*_${{ matrix.arch }}.deb + archive: false retention-days: 14 cli-macos: @@ -304,7 +305,8 @@ jobs: - name: Download debian package uses: actions/download-artifact@v8 with: - pattern: start-registry_*.deb + pattern: start-registry-*.deb + merge-multiple: true - name: Map matrix.arch to docker platform run: | @@ -355,21 +357,73 @@ jobs: EOF + # The container-runtime rootfs runs target-architecture code, so each + # architecture's is built once, on a native runner, for every image that + # this run or its publish builds. + rootfs: + name: Container runtime (${{ matrix.arch }}) + needs: [changes, build] + if: >- + !cancelled() && needs.build.result == 'success' + && needs.changes.outputs.start-os == 'true' + && (needs.changes.outputs.channel != '' || github.event_name != 'pull_request' || needs.changes.outputs.os-image == 'true') + strategy: + fail-fast: false + matrix: + arch: ${{ fromJson(needs.changes.outputs.arches) }} + runs-on: >- + ${{ + fromJson('{ + "x86_64": "ubuntu-latest", + "aarch64": "ubuntu-24.04-arm", + "riscv64": "ubuntu-24.04-riscv" + }')[matrix.arch] + }} + permissions: + contents: read + actions: read + env: + ARCH: ${{ matrix.arch }} + PLATFORM: ${{ matrix.arch }} + steps: + - uses: actions/checkout@v6 + + # Precedes every JavaScript action after checkout. + - name: Update RISC-V action runtime + if: ${{ matrix.arch == 'riscv64' }} + uses: ./.github/actions/riscv-action-runtime + with: + nodejs-version: ${{ env.NODEJS_VERSION }} + + - uses: ./.github/actions/use-compiled-artifacts + with: + arch: ${{ matrix.arch }} + run-id: ${{ github.run_id }} + + - name: Build container runtime rootfs + run: make projects/start-os/container-runtime/rootfs.${{ matrix.arch }}.squashfs + + - uses: actions/upload-artifact@v7 + with: + path: projects/start-os/container-runtime/rootfs.${{ matrix.arch }}.squashfs + archive: false + retention-days: 1 + # A build that does not publish checks the images here: every push outside # master, a dispatch without a channel, and a pull request that touches # image assembly. A publishing build's images are built by startos-iso.yaml. image: name: Image (${{ matrix.platform }}) - needs: [changes, build] + needs: [changes, build, rootfs] if: >- - !cancelled() && needs.build.result == 'success' + !cancelled() && needs.rootfs.result == 'success' && needs.changes.outputs.start-os == 'true' && needs.changes.outputs.channel == '' && (github.event_name != 'pull_request' || needs.changes.outputs.os-image == 'true') strategy: fail-fast: false matrix: platform: ${{ fromJson(needs.changes.outputs.platforms) }} - # Downloading this run's compiled-.tar by run id needs `actions: read`. + # Downloading this run's compiled tarball and rootfs by run id needs `actions: read`. permissions: contents: read actions: read @@ -381,8 +435,8 @@ jobs: publish: name: Publish StartOS - needs: [changes, build] - if: ${{ !cancelled() && needs.build.result == 'success' && needs.changes.outputs.channel != '' }} + needs: [changes, build, rootfs] + if: ${{ !cancelled() && needs.rootfs.result == 'success' && needs.changes.outputs.channel != '' }} runs-on: ubuntu-latest permissions: actions: write diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7e20695a40..f4b336d878 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -120,5 +120,5 @@ jobs: uses: Start9Labs/start-technologies/.github/actions/upload-each@master with: pattern: '*.s9pk' + archive: false retention-days: 14 - compression-level: 0 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6ae8232553..39b00fd8d6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -143,16 +143,13 @@ jobs: with: target: ${{ matrix.target }} - - name: Upload s9pks for Publish stage - uses: actions/upload-artifact@v7 + - name: Upload each s9pk as its own artifact + uses: Start9Labs/start-technologies/.github/actions/upload-each@master with: - # `default` covers the fallback single-entry case where matrix.target - # is empty (package not yet on the new s9pk.mk). - name: build-${{ matrix.target || 'default' }} - path: ./*.s9pk + pattern: '*.s9pk' + archive: false if-no-files-found: error - compression-level: 0 - retention-days: 1 + retention-days: 14 Publish: needs: BuildMatrix @@ -183,10 +180,10 @@ jobs: printf '%s' "${{ secrets.DEV_KEY }}" > ~/.startos/developer.key.pem shell: bash + # BuildMatrix's s9pks are the run's only artifacts. - name: Collect s9pks from BuildMatrix uses: actions/download-artifact@v8 with: - pattern: build-* merge-multiple: true path: . @@ -379,10 +376,3 @@ jobs: start-cli --registry "$REGISTRY" registry package add "$s9pk" --url "${GH_URL}/${s9pk}" done shell: bash - - - name: Upload each s9pk as its own artifact - uses: Start9Labs/start-technologies/.github/actions/upload-each@master - with: - pattern: '*.s9pk' - retention-days: 14 - compression-level: 0 diff --git a/.github/workflows/start-wrt.yaml b/.github/workflows/start-wrt.yaml index 8dd389d240..c7aa72836b 100644 --- a/.github/workflows/start-wrt.yaml +++ b/.github/workflows/start-wrt.yaml @@ -168,13 +168,14 @@ jobs: - name: Verify the image trust store run: make start-wrt-ca-test - - uses: actions/upload-artifact@v7 + # Mirrors build.mk's STARTWRT_BASENAME: the image rule renames the raw + # OpenWrt outputs to startwrt--_spacemit-k1-*.img.gz. + - uses: ./.github/actions/upload-each with: - name: startwrt-openwrt-image - # Mirrors build.mk's STARTWRT_BASENAME: the image rule renames the raw - # OpenWrt outputs to startwrt--_spacemit-k1-*. - path: results/startwrt-* + pattern: results/startwrt-*.img.gz + archive: false retention-days: 14 + if-no-files-found: error # Publish path: upload the built images to shared S3 (the registry CDN serves # them from here) and register + index the version into the beta registry, @@ -250,12 +251,20 @@ jobs: run: | CHANGELOG_REF="${{ github.sha }}" ./scripts/manage-release.sh registry-notes start-wrt > "$RUNNER_TEMP/release-notes.json" - - name: Download image artifact + - name: Download images uses: actions/download-artifact@v8 with: - name: startwrt-openwrt-image + pattern: startwrt-*.img.gz + merge-multiple: true path: artifacts/ + - name: Check downloaded images + working-directory: artifacts + run: | + for file in startwrt-*-sdcard.img.gz startwrt-*-sysupgrade.img.gz; do + [ -f "$file" ] || { echo "::error::No $file artifact in this run"; exit 1; } + done + - name: Install start-cli uses: Start9Labs/start-technologies/.github/actions/install-start-cli@master with: diff --git a/.github/workflows/startos-image.yaml b/.github/workflows/startos-image.yaml index 0af2952411..064799b892 100644 --- a/.github/workflows/startos-image.yaml +++ b/.github/workflows/startos-image.yaml @@ -17,7 +17,7 @@ on: type: string required: true compiled-run-id: - description: Run holding compiled-.tar; empty for this run + description: Run holding compiled-.tar.gz and rootfs..squashfs; empty for this run type: string default: '' commit: @@ -87,76 +87,39 @@ jobs: - name: Ensure hostedtoolcache exists run: sudo mkdir -p /opt/hostedtoolcache && sudo chown "$USER:$USER" /opt/hostedtoolcache - # Actions use the runner's bundled Node, not the Node on GITHUB_PATH. - # V8's background GC threads corrupt the heap on these runners during - # large artifact transfers, so the action host runs `--single-threaded`. - # Its wrapper is bash; dash drops hyphenated `INPUT_*` variables. + - uses: actions/checkout@v6 + with: + ref: ${{ inputs.commit || github.sha }} + fetch-depth: 0 + + # Precedes every JavaScript action after checkout. - name: Update RISC-V action runtime if: ${{ env.ARCH == 'riscv64' }} - run: | - set -euo pipefail - worker="$(readlink -f "/proc/$PPID/exe")" - test "$(basename "$worker")" = Runner.Worker - runner_node="$(dirname "$worker")/../externals/node24/bin/node" - echo "Bundled action runtime: $("$runner_node" --version)" - base="https://unofficial-builds.nodejs.org/download/release/v${NODEJS_VERSION}" - tarball="node-v${NODEJS_VERSION}-linux-riscv64.tar.xz" - cd "$RUNNER_TEMP" - curl -fsSLO "$base/$tarball" - curl -fsSL "$base/SHASUMS256.txt" | grep " $tarball\$" | sha256sum -c - - tar -xJf "$tarball" - node_dir="$RUNNER_TEMP/${tarball%.tar.xz}" - test "$("$node_dir/bin/node" --version)" = "v${NODEJS_VERSION}" - "$node_dir/bin/node" --single-threaded -e 'require("node:crypto").createHash("sha256").update("action-runtime").digest(); console.log(process.versions)' - install -m 755 "$node_dir/bin/node" "$runner_node.real.next" - mv -f "$runner_node.real.next" "$runner_node.real" - printf '#!/bin/bash\nexec "%s" --single-threaded "$@"\n' "$runner_node.real" > "$runner_node.next" - chmod 755 "$runner_node.next" - mv -f "$runner_node.next" "$runner_node" - echo "Updated action runtime: $("$runner_node" --version)" - echo "$node_dir/bin" >> "$GITHUB_PATH" + uses: ./.github/actions/riscv-action-runtime + with: + nodejs-version: ${{ env.NODEJS_VERSION }} - name: Set up docker QEMU uses: docker/setup-qemu-action@v4 - - uses: actions/checkout@v6 - with: - ref: ${{ inputs.commit || github.sha }} - fetch-depth: 0 - - name: Free space run: .github/actions/setup-build/free-disk-space.sh - - name: Download compiled artifacts + - uses: ./.github/actions/use-compiled-artifacts + with: + arch: ${{ env.ARCH }} + run-id: ${{ inputs.compiled-run-id || github.run_id }} + + - name: Download container runtime rootfs uses: actions/download-artifact@v8 with: - name: compiled-${{ env.ARCH }}.tar + name: rootfs.${{ env.ARCH }}.squashfs + path: projects/start-os/container-runtime run-id: ${{ inputs.compiled-run-id || github.run_id }} github-token: ${{ github.token }} - - name: Extract compiled artifacts - run: tar -xvf compiled-${{ env.ARCH }}.tar - - - name: Prevent rebuild of compiled artifacts - run: | - mkdir -p node_modules - mkdir -p projects/start-os/web/dist/raw - mkdir -p projects/start-tunnel/web/dist/raw - mkdir -p shared-libs/crates/start-core/bindings - mkdir -p shared-libs/ts-modules/start-core/lib/osBindings - mkdir -p projects/start-os/container-runtime/node_modules - mkdir -p projects/start-os/container-runtime/dist - mkdir -p projects/start-os/container-runtime/dist/node_modules - mkdir -p projects/start-sdk/dist - mkdir -p shared-libs/ts-modules/start-core/dist - mkdir -p shared-libs/crates/patch-db/client/node_modules - mkdir -p shared-libs/crates/patch-db/client/dist - mkdir -p .angular - mkdir -p projects/start-os/web/dist/raw/ui - mkdir -p projects/start-os/web/dist/raw/setup-wizard - mkdir -p projects/start-os/web/dist/static/ui - mkdir -p projects/start-os/web/dist/static/setup-wizard - make -t compiled-${{ env.ARCH }}.tar + - name: Prevent rebuild of the rootfs + run: make -t projects/start-os/container-runtime/rootfs.${{ env.ARCH }}.squashfs - run: git status @@ -168,6 +131,10 @@ jobs: run: make start-os-img if: ${{ inputs.platform == 'raspberrypi' }} + - name: Compress img + run: gzip results/*.img + if: ${{ inputs.platform == 'raspberrypi' }} + - name: Archive kernel backport packages uses: actions/upload-artifact@v7 if: ${{ inputs.platform == 'x86_64' || inputs.platform == 'aarch64' }} @@ -178,35 +145,32 @@ jobs: retention-days: 14 compression-level: 0 - # Images are already compressed, so the artifacts are stored as-is. + # Release tooling in scripts/ finds these artifacts by file name. - uses: actions/upload-artifact@v7 with: - name: ${{ inputs.platform }}.squashfs path: results/*.squashfs + archive: false retention-days: 14 - compression-level: 0 - uses: actions/upload-artifact@v7 with: - name: ${{ inputs.platform }}.iso path: results/*.iso + archive: false retention-days: 14 - compression-level: 0 if: ${{ inputs.platform != 'raspberrypi' }} - uses: actions/upload-artifact@v7 with: - name: ${{ inputs.platform }}.img - path: results/*.img + path: results/*.img.gz + archive: false retention-days: 14 - compression-level: 0 if: ${{ inputs.platform == 'raspberrypi' }} # The OTA payload legacy (0.3.5.1) boxes pull via their frozen rsync updater: # the 0.4.0 base squashfs (built just above) repackaged onto the published # 0.3.5.1 rootfs. Pure repackaging (no OS compile), so it runs on x86_64 for # every platform. Only platforms that shipped in 0.3.5.1 (no nvidia/riscv); - # raspberrypi requires a reflash (#3443). The .migration.squashfs + # raspberrypi requires a reflash (#3443). The startos-*_.migration.squashfs # artifact is what ops publishes to the frozen registry as the version's OTA # image. See projects/start-os/build/assemble-migration-payload.sh and PR #3399. migration: @@ -227,7 +191,8 @@ jobs: - name: Fetch the 0.4.0 base squashfs uses: actions/download-artifact@v8 with: - name: ${{ inputs.platform }}.squashfs + pattern: startos-*_${{ inputs.platform }}.squashfs + merge-multiple: true path: base-new - name: Fetch the legacy (0.3.5.1) base image @@ -261,8 +226,8 @@ jobs: - uses: actions/upload-artifact@v7 with: - name: ${{ inputs.platform }}.migration.squashfs path: results/*.migration.squashfs + archive: false retention-days: 14 deploy: @@ -293,25 +258,20 @@ jobs: sparse-checkout: scripts/s3-put-once.sh sparse-checkout-cone-mode: false - - name: Download squashfs - uses: actions/download-artifact@v8 - with: - name: ${{ inputs.platform }}.squashfs - path: artifacts/ - - - name: Download ISO - if: ${{ inputs.platform != 'raspberrypi' }} + - name: Download images uses: actions/download-artifact@v8 with: - name: ${{ inputs.platform }}.iso + pattern: startos-*_${{ inputs.platform }}.{squashfs,iso,img.gz} + merge-multiple: true path: artifacts/ - - name: Download IMG - if: ${{ inputs.platform == 'raspberrypi' }} - uses: actions/download-artifact@v8 - with: - name: ${{ inputs.platform }}.img - path: artifacts/ + - name: Check downloaded images + working-directory: artifacts + run: | + image=$([ "$PLATFORM" = raspberrypi ] && echo img.gz || echo iso) + for file in startos-*_"$PLATFORM".squashfs startos-*_"$PLATFORM".$image; do + [ -f "$file" ] || { echo "::error::No $file artifact in this run"; exit 1; } + done - name: Install start-cli uses: Start9Labs/start-technologies/.github/actions/install-start-cli@master @@ -340,7 +300,7 @@ jobs: run: | set -uo pipefail pids=() - for file in *_"$PLATFORM".squashfs *_"$PLATFORM".iso *_"$PLATFORM".img; do + for file in *_"$PLATFORM".squashfs *_"$PLATFORM".iso *_"$PLATFORM".img.gz; do [ -f "$file" ] || continue "$GITHUB_WORKSPACE/scripts/s3-put-once.sh" "$file" "$S3_BUCKET/v$VERSION/$file" & pids+=("$!") @@ -361,8 +321,15 @@ jobs: registered_commit() { jq -er --arg version "$VERSION" '.versions | objects | .[$version].gitHash // ""' <<<"$1" } + # The registry slot a file fills. + slot() { + case "$1" in + *.img.gz) echo img ;; + *) echo "${1##*.}" ;; + esac + } files=() - for file in *_"$PLATFORM".squashfs *_"$PLATFORM".iso *_"$PLATFORM".img; do + for file in *_"$PLATFORM".squashfs *_"$PLATFORM".iso *_"$PLATFORM".img.gz; do [ -f "$file" ] && files+=("$file") done @@ -378,16 +345,22 @@ jobs: index() { if [ "$FORCE_OVERWRITE" = true ]; then - start-cli --registry="$REGISTRY" registry os asset remove "${1##*.}" "$VERSION" "$PLATFORM" || return 1 + start-cli --registry="$REGISTRY" registry os asset remove "$(slot "$1")" "$VERSION" "$PLATFORM" || return 1 + fi + # `asset add` takes the slot from the file extension. The img is + # indexed gzipped, through a hardlink named for its slot. + local indexed=$1 attempt + if [ "$(slot "$1")" = img ]; then + indexed=${1%.gz} + ln -f "$1" "$indexed" || return 1 fi # Adding a file that is already indexed is a no-op, so a failure retries. - local attempt for attempt in 1 2 3; do echo "Indexing $1 for platform $PLATFORM (attempt $attempt)..." start-cli --registry="$REGISTRY" registry os asset add \ --platform="$PLATFORM" \ --version="$VERSION" \ - "$1" \ + "$indexed" \ "$S3_CDN/v$VERSION/$1" && return 0 [ "$attempt" -eq 3 ] || sleep $((attempt * 30)) done @@ -411,11 +384,11 @@ jobs: fi if [ "$commit" != "$COMMIT" ]; then for file in "${files[@]}"; do - jq -e --arg version "$VERSION" --arg kind "${file##*.}" --arg platform "$PLATFORM" \ + jq -e --arg version "$VERSION" --arg kind "$(slot "$file")" --arg platform "$PLATFORM" \ --arg url "$S3_CDN/v$VERSION/$file" \ '.versions[$version][$kind][$platform].urls // [] | any(.[]; . == $url)' \ <<<"$index_json" > /dev/null || continue - start-cli --registry="$REGISTRY" registry os asset remove "${file##*.}" "$VERSION" "$PLATFORM" \ + start-cli --registry="$REGISTRY" registry os asset remove "$(slot "$file")" "$VERSION" "$PLATFORM" \ || echo "::error::could not remove $file from v$VERSION in $REGISTRY" done echo "::error::v$VERSION in $REGISTRY was registered for ${commit:-no commit} while $PLATFORM indexed; this leg's images were withdrawn." @@ -427,7 +400,7 @@ jobs: working-directory: artifacts run: | shopt -s nullglob - printf '%s\n' *_"$PLATFORM".squashfs *_"$PLATFORM".iso *_"$PLATFORM".img > "$RUNNER_TEMP/published-$PLATFORM.txt" + printf '%s\n' *_"$PLATFORM".squashfs *_"$PLATFORM".iso *_"$PLATFORM".img.gz > "$RUNNER_TEMP/published-$PLATFORM.txt" - uses: actions/upload-artifact@v7 with: diff --git a/.github/workflows/startos-iso.yaml b/.github/workflows/startos-iso.yaml index 527f000065..c51cee0a51 100644 --- a/.github/workflows/startos-iso.yaml +++ b/.github/workflows/startos-iso.yaml @@ -10,7 +10,7 @@ on: workflow_dispatch: inputs: build-run-id: - description: build-products.yaml run whose compiled-.tar artifacts to publish + description: build-products.yaml run whose compiled-.tar.gz artifacts to publish type: string required: true commit: @@ -253,10 +253,10 @@ jobs: https://alpha-registry-x.start9.com # Spares every upload that is not indexed yet: another run's deploy # between its upload and its index, and a hand upload into a version - # directory that is already indexed — manage-release.sh's push-gz, or - # the per-platform hotfix that leaves one version legitimately - # referencing two commits. Hand uploads are interactive, so give it - # days. Orphans are permanent; waiting only costs storage. + # directory that is already indexed, such as the per-platform hotfix + # that leaves one version legitimately referencing two commits. Hand + # uploads are interactive, so give it days. Orphans are permanent; + # waiting only costs storage. MIN_AGE_DAYS: 14 run: | set -euo pipefail diff --git a/.gitignore b/.gitignore index 7ffe380b5e..a6f09c5130 100644 --- a/.gitignore +++ b/.gitignore @@ -17,7 +17,7 @@ secrets.db /results /dpkg-workdir /compiled.tar -/compiled-*.tar +/compiled-*.tar.gz /projects/start-os/build/firmware /projects/start-os/build/lib/firmware tmp diff --git a/AGENTS.md b/AGENTS.md index 2c8a3c34cc..1b726663af 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -216,7 +216,7 @@ the source of truth. - **Cutting `/v` is what advances `live-docs` for that product.** StartOS RC tags neither publish books nor consume changelog fragments. [`.github/workflows/docs-sync-on-tag.yml`](.github/workflows/docs-sync-on-tag.yml) takes the tagged tree **whole**, then puts every _other_ `projects/*` back on the release it is on. So a tag moves its own project, the shared libraries beneath it (`shared-libs/`), and the repo root — and nothing another product owns. The shared `projects/start-docs/` site tree rides along only with a product that ships a book, but in `versions.conf` a tag speaks only for its own book's line: other products keep the label `live-docs` publishes, and StartOS and StartWRT tags derive their own from the version (`start-wrt/v1.3.0` publishes under `1.3.x`). The `start-tunnel` and `packaging` lines are hand-maintained and must name the label you want **before** you tag. A bookless release (start-cli, start-registry) still advances its own project and the shared tree; it just leaves the site alone, so no deploy fires. Nothing moves backwards: a tag behind a release already synced — a deb release adopts the commit alpha built, often older than a tag cut before it — still advances its own project but leaves the shared trees where the newer release put them, and a tag behind its own product's last release publishes its book alone. - **Cut every release with [`scripts/manage-release.sh`](scripts/manage-release.sh)** — `./scripts/manage-release.sh release ` (`start-os`, `start-cli`, `start-tunnel`, `start-registry`, `start-sdk`, `start-wrt`); `--help` lists the individual subcommands and env vars. A product's version is read from its manifest (`Cargo.toml`, or `package.json` for the SDK), and its git tag / GitHub release is `/v`. **StartOS is the exception:** its version carries a revision segment SemVer cannot express (`0.4.0.1`), so the **root `package.json`** holds it and `projects/start-os/Cargo.toml` carries only a `0.4.0-rev.1` label — never a comparand, since a SemVer prerelease sorts _below_ its release. Read it via `build/env/version.sh`; see [`shared-libs/crates/start-core/VERSION_BUMP.md`](shared-libs/crates/start-core/VERSION_BUMP.md). - **Release notes are picked, edited, and translated by the release manager, then published from the GitHub release.** `create-gh-release` runs before `tag`. It shows a checkbox picker of the release's non-security fragments for `## Highlights` (`release-notes: true` ones start checked; Tab rewords one for the notes only), compiles the choice and every `security` fragment into the framing, opens the result in `$VISUAL`, `$EDITOR`, or else `sensible-editor` (the picker's Tab uses the same editor), translates the edited English into every locale in `shared-libs/crates/start-core/locales/release-notes.json` with the `claude` CLI, formats every locale with the pinned Prettier, and drafts the GitHub release at the commit being tagged with the locale map attached as `release-notes.json`. That asset is the single source for the notes: the GitHub body shows its English, `index` writes it to the registry, and tag CI (`changelog.mjs sync`) archives every locale onto `master` as `projects//release-notes/[.].md`, so it must exist before the tag is pushed. Re-running `create-gh-release` starts from the uploaded notes and translates again only when the English changed. A release or RC after an RC of the same version starts from that RC's notes, and only fragments added or changed since are offered or added; they are inserted into the matching existing section. `publish-gh-release` takes the draft public once the tag exists. English is the editable source; generated translations bypass the editor. `NO_TRANSLATE=1` publishes English only. `pre-check` fails when `claude` is missing and `NO_TRANSLATE` is unset. -- **StartOS prereleases promote the image alpha already built.** `./scripts/manage-release.sh pre-release start-os` promotes alpha into beta and publishes a GitHub prerelease with a git-only `start-os/v-rc.N` tag; the OS image and registry version remain ``. Every invocation allocates the RC number after the highest RC tag for that version, including another invocation for the same image commit or after a partial failure; a failure before the RC tag is pushed leaves its draft to the next invocation, which reuses that number. Unlike stable `release`, `pre-release` starts a new RC rather than resuming the previous one. The registry's `gitHash` identifies the image commit to tag; a missing hash blocks release rather than guessing from HEAD. `STARTOS_ALPHA_REGISTRY` selects alpha, while `STARTOS_SOURCE_REGISTRY` remains beta (the source for stable release and destination for prerelease). Each prerelease replaces the beta listing for that version by removing its previous entry before promotion. OS images are identical for a given commit: subsequent releases and RCs reuse a published same-version, same-commit prerelease's generated download links, checksums, and signature archive without staging images, uploading gzip copies, or re-signing. Reuse requires its notes, changelog, signature archive, and generated download section; otherwise the ordinary asset flow runs. Notes still receive a final edit, and tagging, GitHub publication, and registry promotion still run. `FORCE=1` runs the ordinary asset flow. Security metadata comes from security changelog fragments owned by that release, including fragments omitted from release notes; metadata refresh preserves the indexed image commit. +- **StartOS prereleases promote the image alpha already built.** `./scripts/manage-release.sh pre-release start-os` promotes alpha into beta and publishes a GitHub prerelease with a git-only `start-os/v-rc.N` tag; the OS image and registry version remain ``. Every invocation allocates the RC number after the highest RC tag for that version, including another invocation for the same image commit or after a partial failure; a failure before the RC tag is pushed leaves its draft to the next invocation, which reuses that number. Unlike stable `release`, `pre-release` starts a new RC rather than resuming the previous one. The registry's `gitHash` identifies the image commit to tag; a missing hash blocks release rather than guessing from HEAD. `STARTOS_ALPHA_REGISTRY` selects alpha, while `STARTOS_SOURCE_REGISTRY` remains beta (the source for stable release and destination for prerelease). Each prerelease replaces the beta listing for that version by removing its previous entry before promotion. OS images are identical for a given commit: subsequent releases and RCs reuse a published same-version, same-commit prerelease's generated download links, checksums, and signature archive without staging images or re-signing. Reuse requires its notes, changelog, signature archive, and generated download section; otherwise the ordinary asset flow runs. Notes still receive a final edit, and tagging, GitHub publication, and registry promotion still run. `FORCE=1` runs the ordinary asset flow. Security metadata comes from security changelog fragments owned by that release, including fragments omitted from release notes; metadata refresh preserves the indexed image commit. - **Release-note files are optional notices, not summaries.** Do not maintain one-sentence release descriptions. Create `projects//release-notes/.md` only for necessary `## Important` notices; otherwise omit it. Important contains actions or warnings for people upgrading: who is affected, what they must do, and when. Put pre-update actions in the pre-update companion instead. Internal rollout prerequisites, publisher coordination, maintainer signing operations, migration implementation details, and verification notes belong in the PR or maintainer release procedure, not Important. A preserved setting needs no notice unless the user must act. `node scripts/changelog.mjs notes projects/ ` compiles Highlights from the fragments the picker checks by default and Security from every `security` fragment, sorted by filename within each section, before the notices; alpha registry notes and the StartOS image's welcome use it. Highlights is a short list of the release's most notable user benefits, not a second changelog: uncheck routine entries in the picker. Section titles come from `shared-libs/crates/start-core/locales/release-notes.json`. `--ref ` reads the tagged snapshot; fetch tags before preparing a build. Already-released notes remain as published. The compiler accepts the legacy `user-facing` field only when reading git snapshots, preserving their original selection; historical tags without selection metadata retain their curated notes. After an update, the StartOS welcome shows the registry notes the updater saved for the installed version, in the server's locale and without the pre-update section. Without them (a sideloaded image, or an update performed by an older release), it falls back to the compiled English notes the image installs as `/usr/lib/startos/release-notes.md`. Put pre-update instructions in optional `.pre-update.md`, headed `## ⚠️ Before You Update`. Optional `..pre-update.md` overrides it for that locale; missing or empty translations fall back to English. GitHub and registry notes include these warnings between `` and `` markers; welcome artifacts exclude them. Every locale's notes must keep the English notes' HTML comments. GitHub output and `manage-release.sh notes ` remain English. Registry notes end with a localized full-changelog link, as does the welcome. The default link opens the published GitHub release. An explicit `CHANGELOG_REF` (used by alpha) links to that ref's pending fragments, then its compiled history. `registry-notes ` produces `{releaseNotes}` with the shared `LocaleString`: an English string without translations, otherwise a locale map including `en_US`. Registries store and promote it unchanged; current StartOS clients select locally with their existing localization pipe and accept English-only registries. Existing compatibility middleware projects English strings for known StartOS clients before 0.4.0.5 and string-only StartWRT clients. Device information, or an explicit update source version without that header, selects compatibility; headerless CLI queries without a source version retain the complete map. @@ -363,7 +363,7 @@ before adding one. `deny.toml` encodes which licenses are accepted. Some pairs of files mirror each other by hand — nothing enforces them, so a change to one half is incomplete until you update the other. Update both in the **same** commit: -- **A product's build inputs in CI ↔ its `build.mk` prerequisites.** StartOS, start-cli, start-registry and start-tunnel build in `.github/workflows/build-products.yaml`, and StartWRT in `.github/workflows/start-wrt.yaml`. Each workflow's `changes` job runs `.github/scripts/classify-event.sh`, which rebuilds only the products a pull request touches, or a push changed since that workflow's last successful push build. `PRODUCTS` in `.github/scripts/changed-products.mjs` is a hand-maintained mirror of the prerequisites in each `projects//build.mk` (the project dir, `shared-libs/**` or the specific crates it pulls in, `Cargo.*`, `build/**`, `debian/**`, the web config for products with a UI, …), and records the workflow that builds each product. When you add or drop a build input in a `build.mk`, update that mirror — otherwise CI will silently stop rebuilding the product on changes that affect it. `OS_IMAGE_PATHS` in the same script carries a finer mirror: on PRs it gates the expensive **image** matrix on image-_assembly_ paths (packaging, image-recipe, systemd units, `apt/**`, shared `build/**`) — the inputs the image target pulls in _beyond_ the compiled binary. When you change what feeds the image target in `projects/start-os/build.mk` (vs. the binary, which the per-target build always covers), update that list too, or image-affecting PRs will skip image validation. +- **A product's build inputs in CI ↔ its `build.mk` prerequisites.** StartOS, start-cli, start-registry and start-tunnel build in `.github/workflows/build-products.yaml`, and StartWRT in `.github/workflows/start-wrt.yaml`. Each workflow's `changes` job runs `.github/scripts/classify-event.sh`, which rebuilds only the products a pull request touches, or a push changed since that workflow's last successful push build. `PRODUCTS` in `.github/scripts/changed-products.mjs` is a hand-maintained mirror of the prerequisites in each `projects//build.mk` (the project dir, `shared-libs/**` or the specific crates it pulls in, `Cargo.*`, `build/**`, `debian/**`, the web config for products with a UI, …), and records the workflow that builds each product. When you add or drop a build input in a `build.mk`, update that mirror — otherwise CI will silently stop rebuilding the product on changes that affect it. `OS_IMAGE_PATHS` in the same script carries a finer mirror: on PRs it gates the expensive **image** matrix on image-_assembly_ paths (packaging, image-recipe, systemd units, the container-runtime rootfs scripts, `apt/**`, shared `build/**`) — the inputs the image target pulls in _beyond_ the compiled binary. When you change what feeds the image target in `projects/start-os/build.mk` (vs. the binary, which the per-target build always covers), update that list too, or image-affecting PRs will skip image validation. - **Pull request retargets run through `.github/workflows/pr-retarget.yml`.** A base change is an `edited` event, but trigger-level `branches:` and `paths:` filters evaluate the new base and diff before a workflow starts. The unfiltered listener therefore calls the explicit base-sensitive set: `test`, `rust-builder`, `build-products`, and `start-wrt`; title and body edits finish in its classifier without replacing existing check conclusions. Keep each called target reusable through `workflow_call`, give its concurrency group a workflow-specific literal prefix, and leave `edited` out of its direct `pull_request:` types. `conflict-markers` remains a direct unfiltered `pull_request` listener and rescans every edit, because its `Conflict Markers` job must itself replace any stale verdict after a retarget. `live-docs-guard` listens directly too, on `pull_request_target` so a fork's PR is checked without waiting for workflow approval: it keeps its `live-docs` branch filter but takes `edited` too, since the filter sees the new base and a PR retargeted onto `live-docs` must be checked before its next push. It reads the changed paths from the API and must never check out the pull request. Grant called jobs their minimum permissions: `packages: write` belongs on the `build-products` and `rust-builder` calls, and `actions: write` on `build-products` for its StartOS publish dispatch. `build-products` confines `packages: write` to `registry-image` and `actions: write` to `publish`, with its build jobs explicitly downgraded to `contents: read`; the builder's `build` and `publish` jobs also request `packages: write` and restrict uploads to master. `.github/workflows/pr-retarget-conflict.yml` reports GitHub's native conflict verdict through its PR-numbered `Mergeability` job; the `pull_request_target` run itself supplies the pending and final check result without writing a commit status. Base changes use mergeability-specific concurrency and poll until GitHub resolves mergeability; other edits finish under a PR-numbered `Metadata edit` job with separate concurrency. When a base-change event's head or base SHA is stale, it cancels its own run so the obsolete check finishes neutral. It never replaces the separate `Conflict Markers` check, whose real head/base scan clears stale marker failures after a clean retarget. The privileged listener must never check out or execute pull request code. `.github/scripts/check-pr-retarget-workflows.py` enforces independent audited target sets, permissions, concurrency, event routing, and conflict-listener isolation. - **start-wrt's CI publish constants ↔ `scripts/manage-release.sh`'s wrt config.** The `deploy` job in `.github/workflows/start-wrt.yaml` registers builds into the beta registry with values (registry URL, S3 CDN, platform, compat floor) and register/index commands that hand-mirror `manage-release.sh`'s `STARTWRT_*` vars and `cmd_register` (the manual fallback). Change one side, change the other. - **StartOS release-note inputs ↔ the StartOS image.** `projects/start-os/build.mk` renders the optional framing and pending fragments for `VERSION.txt` into `/usr/lib/startos/release-notes.md`. The renderer, formatter config, shared locale catalog, optional notices, and fragments are image-assembly inputs. `version/release_notes.rs` reads the packaged file after an update when no saved registry notes match the installed version, and strips the same pre-update markers `scripts/changelog.mjs` writes. Keep `build.mk`, the StartOS entries in `.github/scripts/changed-products.mjs` (`PRODUCTS` and `OS_IMAGE_PATHS`), and `startos-iso.yaml`'s `deploy-prepare` `sparse-checkout` aligned with the renderer's inputs. diff --git a/Makefile b/Makefile index 295fa4eac3..d09fad2a75 100644 --- a/Makefile +++ b/Makefile @@ -59,7 +59,7 @@ format-check: .PHONY: release-notes-test package-ci-test release-notes-test: node --test scripts/tests/*-test.mjs - bash scripts/tests/release-resume-test.sh + bash scripts/tests/release-images-test.sh bash scripts/tests/apt-publish-test.sh package-ci-test: diff --git a/debian/publish.sh b/debian/publish.sh index 6c3c8bf3cf..15808084af 100755 --- a/debian/publish.sh +++ b/debian/publish.sh @@ -121,8 +121,6 @@ sync_down "dists/${SUITE}/" "$REPO_DIR/dists/${SUITE}/" DEB_FILES=() for arg in "$@"; do if [ -d "$arg" ]; then - # `gh run download` leaves a directory per artifact, and the product - # workflows name theirs `_.deb`. while IFS= read -r -d '' f; do DEB_FILES+=("$f") done < <(find "$arg" -type f -name '*.deb' -print0) diff --git a/projects/start-cli/changelog/patch-fixed-gzipped-image-download-names.md b/projects/start-cli/changelog/patch-fixed-gzipped-image-download-names.md new file mode 100644 index 0000000000..8c37e31782 --- /dev/null +++ b/projects/start-cli/changelog/patch-fixed-gzipped-image-download-names.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Preserve the `.gz` suffix when downloading compressed OS and router images with `registry os asset get`. diff --git a/projects/start-os/AGENTS.md b/projects/start-os/AGENTS.md index bb3c12f73f..ab7e87d88c 100644 --- a/projects/start-os/AGENTS.md +++ b/projects/start-os/AGENTS.md @@ -178,7 +178,7 @@ To deploy a **CI build** rather than a local one — no local compile, and the i | `start-os-update-from-gha REMOTE=start9@ RUN_ID=` | A specific Actions run (e.g. an integration PR) | | `start-os-update-from-gha REMOTE=start9@ BRANCH=` | That branch's latest successful build | -It reads the platform off the device, downloads that run's `.squashfs`, and runs the same checksummed upgrade as `start-os-update-squashfs`. Needs `gh` (authenticated), `b3sum`, and `jq`. Squashfs artifacts expire 14 days after the run. `scripts/update-from-gha.sh --help` documents the rest. +It reads the platform off the device, downloads that run's `startos-*_.squashfs`, and runs the same checksummed upgrade as `start-os-update-squashfs`. Needs `gh` (authenticated), `b3sum`, and `jq`. Squashfs artifacts expire 14 days after the run. `scripts/update-from-gha.sh --help` documents the rest. For devices on a different network (uses [magic-wormhole](https://github.com/magic-wormhole/magic-wormhole)): diff --git a/projects/start-os/build.mk b/projects/start-os/build.mk index 880a34070a..147dea2375 100644 --- a/projects/start-os/build.mk +++ b/projects/start-os/build.mk @@ -8,8 +8,9 @@ IMAGE_RECIPE_SRC := $(call ls-files, projects/start-os/build/image-recipe/) STARTD_SRC := projects/start-os/startd.service projects/start-os/services.slice projects/start-os/startos-shutdown.service projects/start-os/startos-restart.service $(BUILD_SRC) STARTOS_RELEASE_NOTES := projects/start-os/release-notes/$(shell cat $(VERSION_FILE)).md STARTOS_RELEASE_NOTES_SRC := scripts/changelog.mjs scripts/changelog-version.mjs shared-libs/crates/start-core/locales/release-notes.json .prettierrc.json package.json $(wildcard $(STARTOS_RELEASE_NOTES)) $(call ls-files, projects/start-os/changelog) -COMPILED_TARGETS := target/$(RUST_ARCH)-unknown-linux-musl/$(PROFILE)/startbox target/$(RUST_ARCH)-unknown-linux-musl/release/start-container target/$(RUST_ARCH)-unknown-linux-musl/release/startos-backup-fs projects/start-os/container-runtime/rootfs.$(ARCH).squashfs -STARTOS_TARGETS := $(STARTD_SRC) $(ENVIRONMENT_FILE) $(GIT_HASH_FILE) $(VERSION_FILE) $(STARTOS_RELEASE_NOTES_SRC) $(COMPILED_TARGETS) $(PLATFORM_FILE) \ +COMPILED_TARGETS := target/$(RUST_ARCH)-unknown-linux-musl/$(PROFILE)/startbox target/$(RUST_ARCH)-unknown-linux-musl/release/start-container target/$(RUST_ARCH)-unknown-linux-musl/release/startos-backup-fs +CONTAINER_RUNTIME_DIST := projects/start-os/container-runtime/dist/index.js projects/start-os/container-runtime/dist/node_modules/.package-lock.json +STARTOS_TARGETS := $(STARTD_SRC) $(ENVIRONMENT_FILE) $(GIT_HASH_FILE) $(VERSION_FILE) $(STARTOS_RELEASE_NOTES_SRC) $(COMPILED_TARGETS) projects/start-os/container-runtime/rootfs.$(ARCH).squashfs $(PLATFORM_FILE) \ $(shell if [ "$(PLATFORM)" = "raspberrypi" ]; then \ echo target/aarch64-unknown-linux-musl/release/pi-beep; \ fi) \ @@ -225,7 +226,7 @@ projects/start-os/container-runtime/dist/node_modules/.package-lock.json project ./projects/start-os/container-runtime/install-dist-deps.sh touch projects/start-os/container-runtime/dist/node_modules/.package-lock.json -projects/start-os/container-runtime/rootfs.$(ARCH).squashfs: projects/start-os/build/lib/resolved.conf projects/start-os/container-runtime/debian.$(ARCH).squashfs projects/start-os/container-runtime/container-runtime.service projects/start-os/container-runtime/update-image.sh projects/start-os/container-runtime/update-image-local.sh projects/start-os/container-runtime/deb-install.sh projects/start-os/container-runtime/dist/index.js projects/start-os/container-runtime/dist/node_modules/.package-lock.json target/$(RUST_ARCH)-unknown-linux-musl/release/start-container +projects/start-os/container-runtime/rootfs.$(ARCH).squashfs: projects/start-os/build/lib/resolved.conf projects/start-os/container-runtime/debian.$(ARCH).squashfs projects/start-os/container-runtime/container-runtime.service projects/start-os/container-runtime/update-image.sh projects/start-os/container-runtime/update-image-local.sh projects/start-os/container-runtime/deb-install.sh $(CONTAINER_RUNTIME_DIST) target/$(RUST_ARCH)-unknown-linux-musl/release/start-container ARCH=$(ARCH) ./projects/start-os/container-runtime/update-image-local.sh projects/start-os/build/lib/depends projects/start-os/build/lib/conflicts: $(ENVIRONMENT_FILE) $(PLATFORM_FILE) $(shell ls projects/start-os/build/dpkg-deps/*) @@ -254,9 +255,10 @@ target/$(RUST_ARCH)-unknown-linux-musl/release/start-container: $(START_CONTAINE ARCH=$(ARCH) PROFILE=release ./build/build-rust-bins.sh start-os:start-container touch target/$(RUST_ARCH)-unknown-linux-musl/release/start-container -# used by github actions -compiled-$(ARCH).tar: $(COMPILED_TARGETS) $(ENVIRONMENT_FILE) $(GIT_HASH_FILE) $(VERSION_FILE) - tar -cvf $@ $^ +# CI's cross-compiled image inputs. Must not run target-architecture code; CI +# builds the container-runtime rootfs on a native runner. +compiled-$(ARCH).tar.gz: $(COMPILED_TARGETS) $(CONTAINER_RUNTIME_DIST) $(ENVIRONMENT_FILE) $(GIT_HASH_FILE) $(VERSION_FILE) + tar -czvf $@ $(COMPILED_TARGETS) projects/start-os/container-runtime/dist $(ENVIRONMENT_FILE) $(GIT_HASH_FILE) $(VERSION_FILE) target/$(RUST_ARCH)-unknown-linux-musl/release/startos-backup-fs: $(call ls-files, projects/start-os/backup-fs) $(BACKUP_PROTOCOL_SRC) Cargo.toml Cargo.lock $(ENVIRONMENT_FILE) $(RUST_ZIG_BUILDER_INPUTS) ARCH=$(ARCH) PROFILE=release ./projects/start-os/backup-fs/build-backup-fs.sh diff --git a/projects/start-os/changelog/patch-changed-raspberrypi-image-format.md b/projects/start-os/changelog/patch-changed-raspberrypi-image-format.md new file mode 100644 index 0000000000..4b621702c5 --- /dev/null +++ b/projects/start-os/changelog/patch-changed-raspberrypi-image-format.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Publish Raspberry Pi images in gzip-compressed `.img.gz` format. diff --git a/projects/start-os/container-runtime/AGENTS.md b/projects/start-os/container-runtime/AGENTS.md index 8279157173..6f34d552c0 100644 --- a/projects/start-os/container-runtime/AGENTS.md +++ b/projects/start-os/container-runtime/AGENTS.md @@ -36,6 +36,7 @@ Tests are Jest + `ts-jest` (`jest.config.js`, `rootDir: ./src`). `mime` is mocke - Compiled JS is installed into the container at `/usr/lib/startos/init/index.js` (the systemd unit runs `start-container pipe-wrap node … /usr/lib/startos/init/index.js`). - `update-image-local.sh` mounts the **repo root** into `start9/build-env` (at `/root/start-os`) and runs `update-image.sh` inside it. `update-image.sh` `cd`s to its own dir (`projects/start-os/container-runtime/`), so it reaches the repo-root build output three levels up — it copies `start-container` from `../../../target/-unknown-linux-musl/release/`. - The squashfs lands at `rootfs..squashfs` and is installed to `/usr/lib/startos/container-runtime/rootfs.squashfs`. +- `update-image.sh` runs target-architecture code (`deb-install.sh` in the chroot), so CI builds the rootfs once per architecture on a native runner, in `build-products.yaml`'s `rootfs` job, not in its cross-compiling build job: `compiled-.tar.gz` carries `dist/` and `start-container` instead, and each image build downloads `rootfs..squashfs`. A pull request changing these scripts or units builds the images through `OS_IMAGE_PATHS` in `.github/scripts/changed-products.mjs`. ## Host effects bindings diff --git a/projects/start-os/container-runtime/ARCHITECTURE.md b/projects/start-os/container-runtime/ARCHITECTURE.md index 177c63d508..33234b1afa 100644 --- a/projects/start-os/container-runtime/ARCHITECTURE.md +++ b/projects/start-os/container-runtime/ARCHITECTURE.md @@ -56,7 +56,7 @@ The runtime ships as a squashfs rootfs baked into the StartOS image: 1. `download-base-image.sh` fetches the Debian trixie LXC base (`debian..squashfs`). 2. `npm run build` compiles `src/` to `dist/`; `install-dist-deps.sh` installs production deps into `dist/node_modules`. -3. `update-image-local.sh` runs `update-image.sh` inside the `start9/build-env` container: it overlays `dist/` into the base at `/usr/lib/startos/init/`, drops in `start-container` and the systemd units, runs `deb-install.sh` in the chroot to upgrade base packages and install runtime dependencies, and mksquashfs's the result to `rootfs..squashfs`. +3. `update-image-local.sh` runs `update-image.sh` inside the `start9/build-env` container: it extracts the base, copies `dist/` into it at `/usr/lib/startos/init/`, drops in `start-container` and the systemd units, runs `deb-install.sh` in the chroot to upgrade base packages and install runtime dependencies, and mksquashfs's the result to `rootfs..squashfs`. The top-level `Makefile` orchestrates all of this (`projects/start-os/container-runtime/rootfs.$(ARCH).squashfs` target); the squashfs is installed to `/usr/lib/startos/container-runtime/rootfs.squashfs` in the final OS image. diff --git a/projects/start-os/container-runtime/update-image-local.sh b/projects/start-os/container-runtime/update-image-local.sh index c92b4e9809..08b39f06b5 100755 --- a/projects/start-os/container-runtime/update-image-local.sh +++ b/projects/start-os/container-runtime/update-image-local.sh @@ -1,5 +1,7 @@ #!/bin/bash +set -e + cd "$(dirname "${BASH_SOURCE[0]}")/../../.." USE_TTY= diff --git a/projects/start-os/container-runtime/update-image.sh b/projects/start-os/container-runtime/update-image.sh index 7a453c2055..0c01afe21b 100755 --- a/projects/start-os/container-runtime/update-image.sh +++ b/projects/start-os/container-runtime/update-image.sh @@ -9,10 +9,9 @@ if [ "$ARCH" = "riscv64" ]; then RUST_ARCH="riscv64gc" fi +# The riscv64 image runner's kernel cannot mount squashfs. mount -t tmpfs tmpfs /tmp -mkdir -p /tmp/lower /tmp/upper /tmp/work /tmp/combined -mount -o loop debian.${ARCH}.squashfs /tmp/lower -mount -t overlay -olowerdir=/tmp/lower,upperdir=/tmp/upper,workdir=/tmp/work overlay /tmp/combined +unsquashfs -q -d /tmp/combined debian.${ARCH}.squashfs mkdir -p /tmp/combined/usr/lib/startos/ cp ../build/lib/resolved.conf /tmp/combined/usr/lib/startos/resolved.conf diff --git a/scripts/generate-forgejo-workflows.cjs b/scripts/generate-forgejo-workflows.cjs index 172c5c81a1..31e07337f8 100644 --- a/scripts/generate-forgejo-workflows.cjs +++ b/scripts/generate-forgejo-workflows.cjs @@ -62,9 +62,10 @@ async function generate(root) { if (step.uses === `${upstream}.github/actions/upload-each@master`) { step.name = 'Upload s9pks' step.uses = `${artifactHost}/upload-artifact@v4` - const { pattern, ...options } = step.with + const { pattern, archive, ...options } = step.with step.with = { ...options, + ...(archive === false && { 'compression-level': 0 }), name: job.strategy?.matrix ? "s9pks-${{ matrix.target || 'default' }}" : 's9pks', diff --git a/scripts/gha-artifact-download.sh b/scripts/gha-artifact-download.sh new file mode 100755 index 0000000000..dca05db8c2 --- /dev/null +++ b/scripts/gha-artifact-download.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# Saves a run's unexpired artifacts whose names match a glob into a directory, +# each as a file named for its artifact: . +# For artifacts uploaded with `archive: false`, which `gh run download` cannot +# fetch (cli/cli#13012). Fails when nothing matches. + +set -euo pipefail + +repo=$1 +run_id=$2 +glob=$3 +dir=$4 +rows=$(gh api --paginate "repos/$repo/actions/runs/$run_id/artifacts?per_page=100" \ + --jq '.artifacts[] | select(.expired | not) | [.id, .name] | @tsv') +mkdir -p "$dir" +found=0 +while IFS=$'\t' read -r id name; do + # shellcheck disable=SC2053 + [[ -n $name && $name == $glob ]] || continue + gh api "repos/$repo/actions/artifacts/$id/zip" > "$dir/$name.part" < /dev/null + mv -f "$dir/$name.part" "$dir/$name" + found=1 +done <<< "$rows" +if [ "$found" = 0 ]; then + >&2 echo "Run $run_id has no unexpired artifact matching $glob" + exit 1 +fi diff --git a/scripts/gha-artifact-run-ids.sh b/scripts/gha-artifact-run-ids.sh index e870ece2c6..1af2c3b8a6 100755 --- a/scripts/gha-artifact-run-ids.sh +++ b/scripts/gha-artifact-run-ids.sh @@ -1,12 +1,28 @@ #!/bin/bash -# Prints the ids of runs on a branch holding an unexpired artifact: -# . +# Prints the ids of runs on a branch holding an unexpired artifact whose name +# matches a glob, newest artifact first: . +# Expiration does not follow listing order. Matching artifacts must be retained +# at most 14 days: the search ends at the first artifact created over 15 days ago. set -euo pipefail -# Reruns preserve run creation time; artifact expiry determines availability. -GHA_ARTIFACT_BRANCH="$3" gh api --method GET --paginate "repos/$1/actions/artifacts" \ - -f name="$2" -F per_page=100 \ - --jq '.artifacts[] - | select((.expired | not) and .workflow_run.head_branch == env.GHA_ARTIFACT_BRANCH) - | .workflow_run.id' | sort -nu +repo=$1 +glob=$2 +branch=$3 +declare -A seen=() +for ((page = 1; ; page++)); do + rows=$(gh api "repos/$repo/actions/artifacts?per_page=100&page=$page" \ + --jq '.artifacts[] | [.name, .expired, .workflow_run.head_branch, .workflow_run.id, + ((.created_at | fromdateiso8601) < (now - 15 * 86400))] | @tsv') + [ -n "$rows" ] || break + while IFS=$'\t' read -r name expired head_branch run_id stale; do + [ "$stale" = false ] || exit 0 + # shellcheck disable=SC2053 + [[ $name == $glob ]] || continue + [ "$expired" = false ] || continue + if [ "$head_branch" = "$branch" ] && [ -z "${seen[$run_id]:-}" ]; then + seen[$run_id]=1 + echo "$run_id" + fi + done <<< "$rows" +done diff --git a/scripts/gha-image-run.sh b/scripts/gha-image-run.sh index 1ec78afade..d98080c8b1 100755 --- a/scripts/gha-image-run.sh +++ b/scripts/gha-image-run.sh @@ -1,13 +1,14 @@ #!/bin/bash # Prints the newest successful image run on a branch holding an unexpired -# .squashfs: . +# startos-*_.squashfs: . set -euo pipefail repo=$1 branch=$2 platform=$3 -run_ids=$("$(dirname "${BASH_SOURCE[0]}")/gha-artifact-run-ids.sh" "$repo" "$platform.squashfs" "$branch") +image="startos-*_$platform.squashfs" +run_ids=$("$(dirname "${BASH_SOURCE[0]}")/gha-artifact-run-ids.sh" "$repo" "$image" "$branch") selected_id=$( for run_id in $run_ids; do gh api "repos/$repo/actions/runs/$run_id" || exit 1 @@ -19,7 +20,7 @@ selected_id=$( ) if [ -z "$selected_id" ]; then - >&2 echo "No successful run on $branch has an unexpired $platform.squashfs artifact" + >&2 echo "No successful run on $branch has an unexpired $image artifact" exit 1 fi printf '%s\n' "$selected_id" diff --git a/scripts/manage-release.sh b/scripts/manage-release.sh index f9435531d4..dd62d52661 100755 --- a/scripts/manage-release.sh +++ b/scripts/manage-release.sh @@ -76,8 +76,8 @@ STARTWRT_TARGET_REGISTRY="${STARTWRT_TARGET_REGISTRY:-https://startwrt-registry. STARTWRT_S3_BUCKET="s3://startwrt-images" STARTWRT_S3_CDN="https://startwrt-images.nyc3.cdn.digitaloceanspaces.com" STARTWRT_PLATFORM="spacemit,k1-x" -# The CI artifact (start-wrt.yaml `image` job) holding both images. -STARTWRT_BUILD_ARTIFACT="startwrt-openwrt-image" +# The CI artifacts (start-wrt.yaml `image` job), one per image. +STARTWRT_BUILD_ARTIFACTS='startwrt-*.img.gz' # Compat floor for `registry os version add`: the oldest installed version # allowed to upgrade to this one. An explicit beta floor (not a `^` caret) keeps # beta prerelease tags in range. The upper bound (<=$VERSION) is added in @@ -359,6 +359,13 @@ os_image_exts() { esac } +os_image_file_ext() { + case "$1" in + img) echo img.gz ;; + *) echo "$1" ;; + esac +} + # Load a registry's OS index into $_INDEX_JSON, refetching only when asked for a # different registry than the one held — a release reads a dozen asset URLs off # it and each fetch is a round trip. Call it once at the top of a scope that @@ -525,34 +532,11 @@ deb_files() { for f in *.deb; do [ -f "$f" ] && echo "$f"; done } -# Compress every raw .img in the release dir beside itself. -# -# The registry keeps indexing the image bare: an installer streams it and the -# signed commitment is over the raw bytes. But a raw card image is mostly -# zeroes, and the release notes hand it to a human on a browser — so the notes -# link the .gz, and it is hashed and signed alongside the bare image. -# -# Idempotent: skips a .gz already newer than its source, and stages through a -# temp file so an interrupted run can't leave a truncated one looking current. -# A no-op outside the os kind — nothing else ships a raw .img. -ensure_img_gz() { - local img - for img in *.img; do - [ -f "$img" ] || continue - if [ -f "${img}.gz" ] && [ ! "$img" -nt "${img}.gz" ]; then - continue - fi - >&2 echo " compressing ${img} -> ${img}.gz" - gzip -c "$img" > "${img}.gz.tmp" - mv -f "${img}.gz.tmp" "${img}.gz" - done -} - # List every file the project ships (for signing / checksums), one per line. release_files() { local f case "$KIND" in - os) for f in *.iso *.img *.img.gz *.squashfs; do [ -f "$f" ] && echo "$f"; done ;; + os) for f in *.iso *.img.gz *.squashfs; do [ -f "$f" ] && echo "$f"; done ;; cli) cli_binaries; deb_files ;; deb) deb_files ;; wrt) for f in *-sdcard.img.gz *-sysupgrade.img.gz; do [ -f "$f" ] && echo "$f"; done ;; @@ -820,8 +804,8 @@ promote_alpha_debs() { pull_gha_debs() { local arch for arch in $DEB_ARCHES; do - echo " ${PROJECT}_${arch}.deb" - gh run download -R "$REPO" "$RUN_ID" -n "${PROJECT}_${arch}.deb" -D "$(pwd)" + echo " ${PROJECT}-*_${arch}.deb" + "$SCRIPT_DIR/gha-artifact-download.sh" "$REPO" "$RUN_ID" "${PROJECT}-*_${arch}.deb" "$(pwd)" done } @@ -872,7 +856,7 @@ release_steps() { case "$KIND" in # create-gh-release drafts the release with the edited notes before the # tag exists: tag CI archives the notes from that draft. - os) echo pre-check pull push-gz create-gh-release tag publish-gh-release index sign ;; + os) echo pre-check pull create-gh-release tag publish-gh-release index sign ;; # Promote the debs CI published to alpha rather than rebuilding # trust from a CI run: what testers have been running is what ships. # (start-cli's per-triple binaries still come from the run — they are @@ -897,14 +881,6 @@ declare -A DONE=() # The commit origin's release tag points at. Empty if untagged. REMOTE_TAG_SHA="" -published_exists() { - [ "$(curl -sI "${APT_NO_CACHE[@]}" -o /dev/null -w '%{http_code}' "$1")" = 200 ] -} - -os_img_gz_origin() { - echo "${S3_ORIGIN}/v${VERSION}/$(basename "$1").gz" -} - detect_progress() { local release assets="" arch triple platform url published=1 DONE=() @@ -927,14 +903,6 @@ detect_progress() { case "$KIND" in os) - for platform in $OS_PLATFORMS; do - [[ " $(os_image_exts "$platform") " == *" img "* ]] || continue - url=$(asset_url "$STARTOS_SOURCE_REGISTRY" img "$platform") - if [ -z "$url" ] || ! published_exists "$(os_img_gz_origin "$url")"; then - published= - fi - done - [ -z "$published" ] || DONE[push-gz]=1 if [ "${PRERELEASE:-}" != 1 ] && [ -z "$(missing_registry_assets "$STARTOS_TARGET_REGISTRY")" ]; then load_registry_index "$STARTOS_TARGET_REGISTRY" if [ "$(jq -r --arg v "$VERSION" '.versions[$v].gitHash // empty' <<< "$_INDEX_JSON")" = "$(tag_commit_sha)" ]; then @@ -1283,11 +1251,11 @@ cmd_pull_gha() { os) for platform in $OS_PLATFORMS; do for ext in $(os_image_exts "$platform"); do - echo " ${platform}.${ext}" - gh run download -R "$REPO" "$RUN_ID" -n "${platform}.${ext}" -D "$(pwd)" + ext=$(os_image_file_ext "$ext") + echo " startos-*_${platform}.${ext}" + "$SCRIPT_DIR/gha-artifact-download.sh" "$REPO" "$RUN_ID" "startos-*_${platform}.${ext}" "$(pwd)" done done - ensure_img_gz ;; cli) pull_gha_cli_binaries @@ -1297,8 +1265,8 @@ cmd_pull_gha() { pull_gha_debs ;; wrt) - echo " ${STARTWRT_BUILD_ARTIFACT} (sdcard + sysupgrade .img.gz)" - gh run download -R "$REPO" "$RUN_ID" -n "$STARTWRT_BUILD_ARTIFACT" -D "$(pwd)" + echo " ${STARTWRT_BUILD_ARTIFACTS} (sdcard + sysupgrade)" + "$SCRIPT_DIR/gha-artifact-download.sh" "$REPO" "$RUN_ID" "$STARTWRT_BUILD_ARTIFACTS" "$(pwd)" ;; esac } @@ -1352,23 +1320,6 @@ matches_commitment() { [ -f "$1" ] && [ "$(b3sum --no-names "$1")" = "$(asset_commitment_b3 "$2" "$3" "$4")" ] } -pull_published_img_gz() { - local img=$1 url tmp digest - url=$(os_img_gz_origin "$img") - published_exists "$url" || return 0 - tmp=$(mktemp "${img}.gz.XXXXXX") - echo " img.gz -> ${img}.gz" - if ! curl -fSL --progress-bar "${APT_NO_CACHE[@]}" "$url" -o "$tmp" \ - || ! digest=$(gzip -dc "$tmp" | b3sum --no-names) \ - || [ "$digest" != "$(b3sum --no-names "$img")" ]; then - rm -f "$tmp" - >&2 echo " ✗ published ${img}.gz does not decompress to the indexed image" - return 1 - fi - touch -r "$img" "$tmp" - mv -f "$tmp" "${img}.gz" -} - cmd_pull() { ensure_release_dir # Released assets replace any GHA-pulled ones, so the marker no longer applies. @@ -1379,8 +1330,8 @@ cmd_pull() { os) # start-cli names its output startos-_., which # drops the commit hash the published basename carries. Land each - # asset under its published name instead, so checksums, signatures, - # and the .gz key all agree with what is actually on S3. + # asset under its published name instead, so checksums and + # signatures agree with what is actually on S3. local platform ext url published tmp stale expected=() load_registry_index "$STARTOS_SOURCE_REGISTRY" for platform in $OS_PLATFORMS; do @@ -1392,7 +1343,6 @@ cmd_pull() { fi published=$(basename "$url") expected+=("$published") - [ "$ext" != img ] || expected+=("${published}.gz") if matches_commitment "$published" "$STARTOS_SOURCE_REGISTRY" "$ext" "$platform"; then echo " ${ext} ${platform} -> ${published} (already here)" else @@ -1402,12 +1352,8 @@ cmd_pull() { mv -f "$tmp"/* "$published" rmdir "$tmp" fi - if [ "$ext" = img ]; then - pull_published_img_gz "$published" || return 1 - fi done done - ensure_img_gz # Everything the notes hash and sign must be named for the S3 object # it links. Anything else the dir has collected — a pull from before # assets were renamed to their published basename, or another build @@ -1506,7 +1452,6 @@ cmd_create_gh_release() ( fi if [ "$KIND" != npm ] && [ -z "${REUSED_OS_RELEASE:-}" ]; then enter_release_dir - ensure_img_gz fi notes_ref=$sha if [ "${PRERELEASE:-}" = 1 ]; then @@ -1546,7 +1491,7 @@ cmd_push() { echo "Uploading OS images to ${S3_BUCKET}/v${VERSION}/ ..." for platform in $OS_PLATFORMS; do for ext in $(os_image_exts "$platform"); do - for file in *_"$platform"."$ext"; do + for file in *_"$platform"."$(os_image_file_ext "$ext")"; do [ -f "$file" ] || continue echo " $file" s3cmd put -P "$file" "${S3_BUCKET}/v${VERSION}/$file" @@ -1584,68 +1529,6 @@ cmd_push() { esac } -# Put the compressed copy of each raw .img beside the bare image on S3. -# -# This adds an object rather than replacing one: the registry keeps pointing at -# the bare .img (see ensure_img_gz), and only the release-notes download link -# moves to the .gz. That link is the indexed URL + ".gz", so the key has to be -# the indexed basename + ".gz" — the guards below exist because any other name -# yields notes that link to nothing. -# -# The local img is picked by content, not name: one platform can be hotfixed -# and re-indexed at a different commit than the rest of the release, and a -# start-cli download drops the hash entirely, so the git hash a basename embeds -# proves nothing. The registry's signed blake3 commitment is what the .gz must -# decompress to; match against that, then rename to the indexed basename so -# checksums and signatures agree with the object the notes link. -cmd_push_gz() { - require_kind os - enter_release_dir - ensure_img_gz - echo "Uploading compressed OS images to ${S3_BUCKET}/v${VERSION}/ ..." - local platform ext url published expected img f - for platform in $OS_PLATFORMS; do - for ext in $(os_image_exts "$platform"); do - [ "$ext" = img ] || continue - url=$(asset_url "$STARTOS_SOURCE_REGISTRY" img "$platform") - if [ -z "$url" ]; then - >&2 echo " ✗ no ${platform} img indexed in ${STARTOS_SOURCE_REGISTRY}" - exit 1 - fi - published=$(basename "$url") - if [ "$url" != "${S3_CDN}/v${VERSION}/${published}" ]; then - >&2 echo " ✗ ${platform} img is indexed at ${url}, outside ${S3_CDN}/v${VERSION}/ — a .gz uploaded to ${S3_BUCKET} would not be reachable at that URL + .gz" - exit 1 - fi - expected=$(asset_commitment_b3 "$STARTOS_SOURCE_REGISTRY" img "$platform") - if [ -z "$expected" ]; then - >&2 echo " ✗ ${published} has no blake3 commitment in ${STARTOS_SOURCE_REGISTRY}" - exit 1 - fi - img= - for f in "$published" *.img; do - [ -f "$f" ] || continue - if [ "$(b3sum --no-names "$f")" = "$expected" ]; then - img=$f - break - fi - done - if [ -z "$img" ]; then - >&2 echo " ✗ no img in $(release_dir) matches the blake3 ${STARTOS_SOURCE_REGISTRY} commits to for ${published} — run 'pull' (or 'pull-gha' with the run that built the indexed img) first" - exit 1 - fi - if [ "$img" != "$published" ]; then - echo " ${img} -> ${published} (renaming to the indexed basename)" - mv -f "$img" "$published" - [ ! -f "${img}.gz" ] || mv -f "${img}.gz" "${published}.gz" - ensure_img_gz - fi - echo " ${published}.gz" - s3cmd put -P "${published}.gz" "${S3_BUCKET}/v${VERSION}/${published}.gz" - done - done -} - cmd_index() { require_kind os wrt local NOTES_FILE @@ -1740,7 +1623,6 @@ cmd_sign() { return fi enter_release_dir - ensure_img_gz resolve_gh_user local files file @@ -1768,7 +1650,6 @@ cmd_sign() { cmd_cosign() { require_kind os cli deb wrt enter_release_dir - ensure_img_gz resolve_gh_user if [ -z "$GH_USER" ] || [ -z "$GH_GPG_KEY" ]; then @@ -1881,7 +1762,7 @@ generated_sections() { url=$(asset_url "$STARTOS_SOURCE_REGISTRY" "$ext" "$platform") [ -n "$url" ] || continue if [ "$ext" = img ]; then - url="${url}.gz \"gzip-compressed — Raspberry Pi Imager and balenaEtcher flash it without unpacking\"" + url="${url} \"gzip-compressed — Raspberry Pi Imager and balenaEtcher flash it without unpacking\"" fi echo "| ${hardware} | ${image} | [${ext^^}](${url}) |" done @@ -1965,7 +1846,6 @@ cmd_body() { require_kind os cli deb npm wrt if [ "$KIND" != npm ]; then enter_release_dir - ensure_img_gz fi local changelog changelog=$(cd "$REPO_ROOT" && node scripts/changelog.mjs render "projects/$PROJECT" "$VERSION") @@ -2002,7 +1882,7 @@ cmd_release() { for step in $(release_steps); do if [ -n "$REUSED_OS_RELEASE" ]; then case "$step" in - pull | push-gz) + pull) echo "Skipping ${step}: reusing assets from $(jq -r .tagName <<< "$REUSED_OS_RELEASE")." continue ;; @@ -2034,8 +1914,8 @@ usage() { Usage: manage-release.sh Projects: - start-os OS images (iso/squashfs, raspberrypi img) -> S3 + registry - OS index; the raw img also gets a .gz on S3 for the notes + start-os OS images (iso/squashfs, raspberrypi img.gz) -> S3 + registry + OS index start-cli per-triple binaries -> GitHub release; per-arch .deb -> apt + GitHub start-tunnel per-arch .deb -> apt repo + GitHub release start-registry per-arch .deb -> apt repo + GitHub release @@ -2101,10 +1981,6 @@ Subcommands: push Upload artifacts to their destination (S3 for os, GitHub release + apt for cli/deb, npm publish for sdk). For os this normally runs in CI; use it for a manual re-publish. - push-gz os only: compress each raw .img and upload the .gz beside - the bare image on S3 — the registry keeps indexing the bare - image; only the release-notes download link uses the .gz. - Run 'pull' (or 'pull-gha') first. index Set the release's edited notes on the source registry and promote the version into the production registry. (os: pre-release promotes alpha into beta. wrt: CI indexes into @@ -2207,7 +2083,6 @@ case "$SUBCOMMAND" in create-gh-release) cmd_create_gh_release ;; publish-gh-release) cmd_publish_gh_release ;; push) cmd_push ;; - push-gz) cmd_push_gz ;; index) cmd_index ;; register) cmd_register ;; sign) cmd_sign ;; diff --git a/scripts/tests/gha-artifact-download-test.mjs b/scripts/tests/gha-artifact-download-test.mjs new file mode 100644 index 0000000000..c7aec4c559 --- /dev/null +++ b/scripts/tests/gha-artifact-download-test.mjs @@ -0,0 +1,63 @@ +import assert from 'node:assert/strict' +import { readdirSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { test } from 'node:test' +import { REPO } from './fixtures.mjs' +import { artifactFixture } from './gha-artifact-fixture.mjs' + +function download(t, runs, glob) { + const f = artifactFixture(t, runs) + const result = f.run( + 'bash', + [ + join(REPO, 'scripts/gha-artifact-download.sh'), + 'Start9Labs/start-technologies', + '7', + glob, + 'out', + ], + { env: f.env, encoding: 'utf8' }, + ) + const dir = join(f.root, 'out') + return { result, dir, files: () => readdirSync(dir).sort() } +} + +test('saves each unexpired matching artifact of the run under its name', t => { + const { result, dir, files } = download( + t, + [ + { + id: 7, + artifacts: [ + 'start-cli-0.4.0-aaaaaaa_x86_64.deb', + 'start-cli-0.4.0-aaaaaaa_aarch64.deb', + { name: 'start-cli-0.4.0-aaaaaaa_riscv64.deb', expired: true }, + 'start-tunnel-0.4.0-aaaaaaa_x86_64.deb', + 'start-cli_x86_64-unknown-linux-musl', + ], + }, + { id: 8, artifacts: ['start-cli-0.4.0-bbbbbbb_x86_64.deb'] }, + ], + 'start-cli-*.deb', + ) + assert.equal(result.status, 0, result.stdout + result.stderr) + assert.deepEqual(files(), [ + 'start-cli-0.4.0-aaaaaaa_aarch64.deb', + 'start-cli-0.4.0-aaaaaaa_x86_64.deb', + ]) + assert.equal( + readFileSync(join(dir, 'start-cli-0.4.0-aaaaaaa_x86_64.deb'), 'utf8'), + 'start-cli-0.4.0-aaaaaaa_x86_64.deb contents\n', + ) +}) + +test('fails when the run holds no matching artifact', t => { + const { result, files } = download( + t, + [{ id: 7, artifacts: ['x86_64.squashfs'] }], + 'startos-*_x86_64.squashfs', + ) + assert.notEqual(result.status, 0) + assert.match(result.stderr, /no unexpired artifact matching/) + assert.deepEqual(files(), []) +}) diff --git a/scripts/tests/gha-artifact-fixture.mjs b/scripts/tests/gha-artifact-fixture.mjs index ad2450c4d2..001154fdfa 100644 --- a/scripts/tests/gha-artifact-fixture.mjs +++ b/scripts/tests/gha-artifact-fixture.mjs @@ -4,8 +4,11 @@ import { REPO, fixture } from './fixtures.mjs' export function artifactFixture(t, runs) { const f = fixture(t) - const helper = 'scripts/gha-artifact-run-ids.sh' - chmodSync(f.write(helper, readFileSync(join(REPO, helper))), 0o755) + for (const helper of [ + 'scripts/gha-artifact-run-ids.sh', + 'scripts/gha-artifact-download.sh', + ]) + chmodSync(f.write(helper, readFileSync(join(REPO, helper))), 0o755) f.write('runs.json', JSON.stringify(runs)) f.write('gh.log', '') f.write('downloads.log', '') @@ -17,23 +20,33 @@ const root = ${JSON.stringify(f.root)} const runs = JSON.parse(readFileSync(root + '/runs.json')) const args = process.argv.slice(2) appendFileSync(root + '/gh.log', JSON.stringify(args) + '\\n') -const artifacts = run => run.artifacts.map(artifact => ({ +const artifacts = run => run.artifacts.map((artifact, index) => ({ + id: run.id * 1000 + index, expired: false, + created_at: run.created_at ?? new Date().toISOString().replace(/\\.\\d+Z$/, 'Z'), ...(typeof artifact === 'string' ? { name: artifact } : artifact), workflow_run: { id: run.id, head_branch: run.head_branch }, })) +const newestFirst = (a, b) => + b.created_at.localeCompare(a.created_at) || b.workflow_run.id - a.workflow_run.id if (args[0] === 'api') { const url = args.find(arg => arg.startsWith('repos/')) if (process.env.GH_FAIL_MATCH && url.includes(process.env.GH_FAIL_MATCH)) process.exit(17) + const page = Number(new URL('https://x/' + url).searchParams.get('page') ?? 1) let response const workflow = url.match(/workflows\\/([^/]+)\\/runs/) const run = url.match(/actions\\/runs\\/(\\d+)(\\/artifacts)?/) - if (url.endsWith('/actions/artifacts')) { - const name = args.find(arg => arg.startsWith('name=')).slice(5) - const matching = runs.flatMap(artifacts).filter(artifact => artifact.name === name) - response = { artifacts: args.includes('--paginate') ? matching : matching.slice(0, 100) } + const zip = url.match(/actions\\/artifacts\\/(\\d+)\\/zip$/) + if (/\\/actions\\/artifacts(\\?|$)/.test(url)) { + const all = runs.flatMap(artifacts).sort(newestFirst) + response = { artifacts: all.slice((page - 1) * 100, page * 100) } + } else if (zip) { + const found = runs.flatMap(artifacts).find(artifact => String(artifact.id) === zip[1]) + if (!found) process.exit(22) + appendFileSync(root + '/downloads.log', found.workflow_run.id + ' ' + found.name + '\\n') + process.stdout.write(found.name + ' contents\\n') + process.exit(0) } else if (workflow) { - const page = Number(new URL('https://x/' + url).searchParams.get('page') ?? 1) const matching = runs.filter(run => run.path === '.github/workflows/' + workflow[1]) .sort((a, b) => b.created_at.localeCompare(a.created_at)) response = { workflow_runs: matching.slice((page - 1) * 100, page * 100) } @@ -52,8 +65,6 @@ if (args[0] === 'api') { process.exit(result.status) } console.log(JSON.stringify(args.includes('--slurp') ? [response] : response)) -} else if (args[0] === 'run' && args[1] === 'download') { - appendFileSync(root + '/downloads.log', args[4] + ' ' + args[args.indexOf('-p') + 1] + '\\n') } else process.exit(2) `, ) diff --git a/scripts/tests/gha-artifact-run-ids-test.mjs b/scripts/tests/gha-artifact-run-ids-test.mjs index 6bc17c396d..49ccbefbbf 100644 --- a/scripts/tests/gha-artifact-run-ids-test.mjs +++ b/scripts/tests/gha-artifact-run-ids-test.mjs @@ -4,47 +4,84 @@ import { test } from 'node:test' import { REPO } from './fixtures.mjs' import { artifactFixture } from './gha-artifact-fixture.mjs' -const IMAGE = 'x86_64.squashfs' +const GLOB = 'startos-*_x86_64.squashfs' +const image = (hash, platform = 'x86_64') => + `startos-0.4.0-${hash}_${platform}.squashfs` const run = (id, head_branch, artifacts) => ({ id, head_branch, artifacts }) function discover(t, runs, env = {}) { const f = artifactFixture(t, runs) - return f.run( + const result = f.run( 'bash', [ join(REPO, 'scripts/gha-artifact-run-ids.sh'), 'Start9Labs/start-technologies', - IMAGE, + GLOB, 'master', ], { env: { ...f.env, ...env }, encoding: 'utf8' }, ) + return { result, calls: f.calls() } } -test('discovery selects unexpired artifacts for the requested branch', t => { - const result = discover(t, [ - run(1, 'master', [IMAGE]), - run(2, 'master', [{ name: IMAGE, expired: true }]), - run(3, 'integration/other', [IMAGE]), - run(4, 'master', ['aarch64.squashfs']), +test('discovery selects unexpired matching artifacts for the requested branch, newest first', t => { + const { result } = discover(t, [ + run(1, 'master', [image('aaaaaaa')]), + run(2, 'master', [image('bbbbbbb')]), + run(3, 'integration/other', [image('ccccccc')]), + run(4, 'master', [ + image('ddddddd', 'aarch64'), + image('ddddddd', 'x86_64-nonfree'), + 'startos-0.4.0-ddddddd_x86_64.migration.squashfs', + ]), ]) assert.equal(result.status, 0, result.stdout + result.stderr) - assert.equal(result.stdout.trim(), '1') + assert.deepEqual(result.stdout.trim().split('\n'), ['2', '1']) }) test('discovery includes matching artifacts beyond the first page', t => { - const result = discover(t, [ + const { result } = discover(t, [ + run(1, 'master', [image('aaaaaaa')]), ...Array.from({ length: 101 }, (_, index) => - run(index + 1, 'integration/other', [IMAGE]), + run(index + 2, 'integration/other', ['start-cli_x86_64.deb']), ), - run(200, 'master', [IMAGE]), ]) assert.equal(result.status, 0, result.stdout + result.stderr) - assert.equal(result.stdout.trim(), '200') + assert.equal(result.stdout.trim(), '1') +}) + +test('expired matches do not hide unexpired artifacts on later pages', t => { + const { result } = discover(t, [ + run(1, 'master', [image('aaaaaaa')]), + ...Array.from({ length: 150 }, (_, index) => + run(index + 2, 'integration/other', ['start-cli_x86_64.deb']), + ), + run(200, 'integration/other', [{ name: image('bbbbbbb'), expired: true }]), + run(201, 'master', [image('ccccccc')]), + ]) + assert.equal(result.status, 0, result.stdout + result.stderr) + assert.deepEqual(result.stdout.trim().split('\n'), ['201', '1']) +}) + +test('discovery stops paging at an artifact created over 15 days ago', t => { + const old = new Date(Date.now() - 16 * 86400e3) + .toISOString() + .replace(/\.\d+Z$/, 'Z') + const { result, calls } = discover(t, [ + run(1, 'master', [image('aaaaaaa')]), + ...Array.from({ length: 150 }, (_, index) => ({ + ...run(index + 2, 'integration/other', ['start-cli_x86_64.deb']), + created_at: old, + })), + run(201, 'master', [image('ccccccc')]), + ]) + assert.equal(result.status, 0, result.stdout + result.stderr) + assert.deepEqual(result.stdout.trim().split('\n'), ['201', '1']) + assert.equal(calls.length, 1) }) test('artifact discovery propagates API failures', t => { - const result = discover(t, [run(1, 'master', [IMAGE])], { + const { result } = discover(t, [run(1, 'master', [image('aaaaaaa')])], { GH_FAIL_MATCH: '/actions/artifacts', }) assert.notEqual(result.status, 0) diff --git a/scripts/tests/gha-image-run-test.mjs b/scripts/tests/gha-image-run-test.mjs index 852b563941..6a63de2824 100644 --- a/scripts/tests/gha-image-run-test.mjs +++ b/scripts/tests/gha-image-run-test.mjs @@ -14,7 +14,7 @@ const run = (id, artifacts, overrides = {}) => ({ artifacts, ...overrides, }) -const IMAGE = 'x86_64.squashfs' +const IMAGE = 'startos-0.4.0-aaaaaaa_x86_64.squashfs' function select(t, workflows) { const runs = Object.entries(workflows).flatMap(([workflow, pages]) => @@ -44,7 +44,7 @@ for (const [name, workflows, expected] of [ 'skips a newer successful product-only build', { 'build-products.yaml': [ - [run(3, ['start-cli_x86_64.deb']), run(2, [IMAGE])], + [run(3, ['start-cli-0.4.0-aaaaaaa_x86_64.deb']), run(2, [IMAGE])], ], }, '2', @@ -61,11 +61,21 @@ for (const [name, workflows, expected] of [ 'ignores expired and other-platform images', { 'startos-iso.yaml': [ - [run(3, [], { artifacts: [{ name: IMAGE, expired: true }] })], + [run(1, [], { artifacts: [{ name: IMAGE, expired: true }] })], + ], + 'build-products.yaml': [ + [ + run(4, [ + 'startos-0.4.0-aaaaaaa_aarch64.squashfs', + 'startos-0.4.0-aaaaaaa_x86_64-nonfree.squashfs', + 'startos-0.4.0-aaaaaaa_x86_64.migration.squashfs', + ]), + run(3, [IMAGE]), + run(2, [IMAGE], { conclusion: 'failure' }), + ], ], - 'build-products.yaml': [[run(2, ['aarch64.squashfs']), run(1, [IMAGE])]], }, - '1', + '3', ], [ 'images from other branches do not hide the requested branch', @@ -87,7 +97,9 @@ for (const [name, workflows, expected] of [ ], [ 'fails when no requested image remains', - { 'build-products.yaml': [[run(1, ['start-cli_x86_64.deb'])]] }, + { + 'build-products.yaml': [[run(1, ['start-cli-0.4.0-aaaaaaa_x86_64.deb'])]], + }, null, ], ]) { @@ -105,8 +117,10 @@ test('image run selection: an older rerun can hold an unexpired image', t => { const result = select(t, { 'build-products.yaml': [ [ - run(1, [IMAGE], { - created_at: new Date(Date.now() - 20 * 86400e3).toISOString(), + run(1, [{ name: IMAGE, created_at: run(9).created_at }], { + created_at: new Date(Date.now() - 20 * 86400e3) + .toISOString() + .replace(/\.\d+Z$/, 'Z'), run_attempt: 2, }), ], diff --git a/scripts/tests/prerelease-test.mjs b/scripts/tests/prerelease-test.mjs index 7cd56efb78..7f014c7b60 100644 --- a/scripts/tests/prerelease-test.mjs +++ b/scripts/tests/prerelease-test.mjs @@ -195,7 +195,6 @@ cmd_pull() { mkdir -p "$(release_dir)" printf image > "$(release_dir)/image.iso" } -cmd_push_gz() { :; } cmd_sign() { if [ -n "\${REUSED_OS_RELEASE:-}" ]; then (eval "$production_sign"; cmd_sign) @@ -338,7 +337,6 @@ appendFileSync(process.argv[2], '\\nFinal release edit.\\n') eval "$production_sign" gpg() { echo 'unexpected signing-key access' >&2; return 91; } cmd_pull() { echo 'unexpected image download' >&2; return 92; } -cmd_push_gz() { echo 'unexpected image upload' >&2; return 93; } `, 'cmd_release', ) @@ -376,7 +374,6 @@ test('a repeated same-commit prerelease copies the prior signatures and checksum eval "$production_sign" gpg() { return 91; } cmd_pull() { return 92; } -cmd_push_gz() { return 93; } `, ) const second = data(`start-os_v${VERSION}-rc.2.json`) @@ -392,7 +389,6 @@ test('a failed signature copy resumes without downloading images or signing agai eval "$production_sign" gpg() { return 91; } cmd_pull() { return 92; } -cmd_push_gz() { return 93; } ` release(false, reuseOnly, 'cmd_release') const stable = data(`start-os_v${VERSION}.json`) diff --git a/scripts/tests/release-images-test.sh b/scripts/tests/release-images-test.sh new file mode 100644 index 0000000000..2d0b972075 --- /dev/null +++ b/scripts/tests/release-images-test.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +source <(awk '/^SUBCOMMAND=/{exit} {print}' "$ROOT/scripts/manage-release.sh") +REPO_ROOT=$ROOT +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT +PROJECT=start-os +KIND=os +VERSION=1.2.3 +TAG=start-os/v1.2.3 +OS_PLATFORMS=raspberrypi +mkdir -p "$TMP/published" + +b3sum() { + if [ "${1:-}" = --no-names ]; then + sha256sum "$2" | cut -d' ' -f1 + else + sha256sum "$@" + fi +} +load_registry_index() { :; } +resolve_os_commit() { :; } +reusable_os_release() { :; } +asset_url() { + [ "$2" != img ] || echo "$S3_CDN/v$VERSION/$PUBLISHED" +} +asset_commitment_b3() { b3sum --no-names "$TMP/published/$PUBLISHED"; } +# start-cli names its download for the slot, not the published file. +start-cli() { + cp "$TMP/published/$PUBLISHED" "${@: -1}/startos-${VERSION}_raspberrypi.img" +} + +cmd_pre_check() { + DONE[tag]=1 + DONE[create-gh-release]=1 + DONE[publish-gh-release]=1 + DONE[index]=1 +} +cmd_sign() { + [ "$(release_files)" = "$PUBLISHED" ] + cmp "$TMP/published/$PUBLISHED" "$(release_dir)/$PUBLISHED" +} +HOME=$TMP/release/home +PUBLISHED=startos-1.2.3-abc_raspberrypi.img.gz +printf 'published image\n' | gzip -c > "$TMP/published/$PUBLISHED" +cmd_release +notes=$(generated_sections) +grep -Fq "$S3_CDN/v$VERSION/$PUBLISHED" <<< "$notes" +grep -Fq " $PUBLISHED" <<< "$notes" +grep -Fq 'gzip-compressed' <<< "$notes" + +HOME=$TMP/gha/home +resolve_gha_run() { RUN_ID=1; RUN_SHA=abc; ensure_release_dir; } +SCRIPT_DIR=$TMP/bin +mkdir -p "$SCRIPT_DIR" +export CI_IMG=$TMP/published/$PUBLISHED +cat > "$SCRIPT_DIR/gha-artifact-download.sh" <<'SCRIPT' +#!/bin/bash +case "$3" in + 'startos-*_raspberrypi.img.gz') cp "$CI_IMG" "$4/startos-1.2.3-def_raspberrypi.img.gz" ;; + 'startos-*_raspberrypi.squashfs') : > "$4/startos-1.2.3-def_raspberrypi.squashfs" ;; + *) echo "unexpected artifact $3" >&2; exit 1 ;; +esac +SCRIPT +chmod +x "$SCRIPT_DIR/gha-artifact-download.sh" +(cmd_pull_gha) +cmp "$CI_IMG" "$(release_dir)/startos-1.2.3-def_raspberrypi.img.gz" +[ ! -e "$(release_dir)/startos-1.2.3-def_raspberrypi.img" ] +echo 'Release image tests passed.' diff --git a/scripts/tests/release-resume-test.sh b/scripts/tests/release-resume-test.sh deleted file mode 100644 index 473c0e0805..0000000000 --- a/scripts/tests/release-resume-test.sh +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) -source <(awk '/^SUBCOMMAND=/{exit} {print}' "$ROOT/scripts/manage-release.sh") -REPO_ROOT=$ROOT -TMP=$(mktemp -d) -trap 'rm -rf "$TMP"' EXIT -HOME=$TMP/home -PROJECT=start-os -KIND=os -VERSION=1.2.3 -TAG=start-os/v1.2.3 -OS_PLATFORMS=raspberrypi -mkdir -p "$TMP/published" -printf 'published image\n' > "$TMP/published/image.img" -touch -t 202001010000 "$TMP/published/image.img" -gzip -c "$TMP/published/image.img" > "$TMP/published/image.img.gz" - -b3sum() { - if [ "$#" -eq 2 ]; then sha256sum "$2"; else sha256sum; fi | cut -d' ' -f1 -} -load_registry_index() { :; } -resolve_os_commit() { :; } -reusable_os_release() { :; } -asset_url() { - [ "$2" != img ] || echo "$S3_CDN/v$VERSION/image.img" -} -asset_commitment_b3() { b3sum --no-names "$TMP/published/image.img"; } -start-cli() { - cp "$TMP/published/image.img" "${@: -1}/download.img" -} -published_exists() { [ "${PUBLISHED_GZ:-1}" = 1 ]; } -curl() { - local output="" arg - while [ "$#" -gt 0 ]; do - arg=$1 - shift - if [ "$arg" = -o ]; then output=$1; shift; fi - done - cp "$TMP/published/image.img.gz" "$output" -} - -cmd_pre_check() { - DONE[push-gz]=1 - DONE[tag]=1 - DONE[create-gh-release]=1 - DONE[publish-gh-release]=1 - DONE[index]=1 -} -cmd_sign() { - cmp "$TMP/published/image.img.gz" "$(release_dir)/image.img.gz" -} -cmd_release -cmd_pull -ensure_img_gz -cmp "$TMP/published/image.img.gz" "$(release_dir)/image.img.gz" - -rm -f "$(release_dir)/image.img.gz" -PUBLISHED_GZ=0 -cmd_pull -gzip -dc "$(release_dir)/image.img.gz" | cmp "$TMP/published/image.img" - - -PUBLISHED_GZ=1 -rm -f "$(release_dir)/image.img.gz" -printf 'wrong image\n' | gzip -c > "$TMP/published/image.img.gz" -if (cmd_pull); then - echo 'Mismatched published gzip was accepted' >&2 - exit 1 -fi -[ ! -f "$(release_dir)/image.img.gz" ] -printf 'not a gzip\n' > "$TMP/published/image.img.gz" -if (cmd_pull); then - echo 'Corrupt published gzip was accepted' >&2 - exit 1 -fi -[ ! -f "$(release_dir)/image.img.gz" ] -echo 'Release gzip resume tests passed.' diff --git a/scripts/update-from-gha.sh b/scripts/update-from-gha.sh index 011cd15f9c..ec9136e167 100755 --- a/scripts/update-from-gha.sh +++ b/scripts/update-from-gha.sh @@ -141,14 +141,12 @@ else trap 'rm -rf "$DOWNLOAD_DIR"' EXIT fi -echo "Downloading ${PLATFORM}.squashfs from run $RUN_ID..." -gh run download -R "$REPO" "$RUN_ID" -n "${PLATFORM}.squashfs" -D "$DOWNLOAD_DIR" - -SQUASHFS=$(find "$DOWNLOAD_DIR" -name '*.squashfs' -type f | head -n1) -if [ -z "$SQUASHFS" ]; then - >&2 echo "Run $RUN_ID has no ${PLATFORM}.squashfs artifact (expired, or that platform was not built)" +echo "Downloading the ${PLATFORM} squashfs from run $RUN_ID..." +if ! "$(dirname "${BASH_SOURCE[0]}")/gha-artifact-download.sh" "$REPO" "$RUN_ID" "startos-*_${PLATFORM}.squashfs" "$DOWNLOAD_DIR"; then + >&2 echo "(expired, that platform was not built, or the run predates unarchived image artifacts)" exit 1 fi +SQUASHFS=$(find "$DOWNLOAD_DIR" -name "startos-*_${PLATFORM}.squashfs" -type f | head -n1) # The upgrade script compares against the first half of the blake3 hash, the # same truncation start-os-update-squashfs passes. diff --git a/shared-libs/crates/start-core/src/registry/os/asset/get.rs b/shared-libs/crates/start-core/src/registry/os/asset/get.rs index 5985726800..71da282c4f 100644 --- a/shared-libs/crates/start-core/src/registry/os/asset/get.rs +++ b/shared-libs/crates/start-core/src/registry/os/asset/get.rs @@ -8,6 +8,7 @@ use imbl_value::{InternedString, json}; use itertools::Itertools; use rpc_toolkit::{Context, HandlerArgs, HandlerExt, ParentHandler, from_fn_async}; use serde::{Deserialize, Serialize}; +use url::Url; use crate::context::CliContext; use crate::prelude::*; @@ -173,7 +174,7 @@ async fn cli_get_os_asset( res.validate(SIG_CONTEXT, res.all_signers())?; - let download = download.join(format!("startos-{version}_{platform}.{ext}")); + let download = download.join(download_file_name(&version, &platform, ext, &res.urls)); let mut file = AtomicFile::new(&download, None::<&Path>).await?; let progress = FullProgressTracker::new(); @@ -211,3 +212,55 @@ async fn cli_get_os_asset( Ok(res) } + +/// Ends in `.gz` when every URL serving the asset names a `.gz` file. +fn download_file_name( + version: &impl std::fmt::Display, + platform: &impl std::fmt::Display, + ext: &str, + urls: &[Url], +) -> String { + let gzipped = !urls.is_empty() && urls.iter().all(|url| url.path().ends_with(".gz")); + format!( + "startos-{version}_{platform}.{ext}{}", + if gzipped { ".gz" } else { "" } + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn urls(paths: &[&str]) -> Vec { + paths + .iter() + .map(|path| Url::parse(&format!("https://cdn.example{path}")).unwrap()) + .collect() + } + + #[test] + fn download_keeps_the_gzip_suffix_of_its_urls() { + assert_eq!( + download_file_name( + &"0.4.3", + &"raspberrypi", + "img", + &urls(&["/v0.4.3/a_raspberrypi.img.gz"]) + ), + "startos-0.4.3_raspberrypi.img.gz" + ); + assert_eq!( + download_file_name( + &"0.4.3", + &"raspberrypi", + "img", + &urls(&["/v0.4.3/a_raspberrypi.img"]) + ), + "startos-0.4.3_raspberrypi.img" + ); + assert_eq!( + download_file_name(&"0.4.3", &"x86_64", "iso", &urls(&["/v0.4.3/a.iso?x=1.gz"])), + "startos-0.4.3_x86_64.iso" + ); + } +} From 11fc229461722514be8f4b950aa5aa7d24fe2eb0 Mon Sep 17 00:00:00 2001 From: Helix the Red <355572797+helix-red@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:42:18 -0700 Subject: [PATCH 17/38] fix(core): rescan gateways when a device gains its IP interface (#4790) NetworkManager publishes a device's `IpInterface` only once activation reaches IP_CHECK (`update_prop_ip_iface` in NM 1.52). A WireGuard device that is created or re-realized triggers `DeviceAdded` while it is still unnamed, so the gateway watcher's scan skipped it and subscribed to nothing on it. The later name change is announced only on the device, so the gateway never gained `ipInfo` until an unrelated manager-level event (a reboot, another device appearing) caused another scan. The scan now watches every device's `IpInterface` and rescans when it differs from what the scan observed, so activation and deactivation reach the watcher and policy-routing reconciliation directly. Closes #4784 Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --- ...patch-fixed-wireguard-gateway-discovery.md | 5 + shared-libs/crates/start-core/Cargo.toml | 1 + .../crates/start-core/src/net/gateway.rs | 176 +++++++++++++++++- 3 files changed, 172 insertions(+), 10 deletions(-) create mode 100644 projects/start-os/changelog/patch-fixed-wireguard-gateway-discovery.md diff --git a/projects/start-os/changelog/patch-fixed-wireguard-gateway-discovery.md b/projects/start-os/changelog/patch-fixed-wireguard-gateway-discovery.md new file mode 100644 index 0000000000..0a18386859 --- /dev/null +++ b/projects/start-os/changelog/patch-fixed-wireguard-gateway-discovery.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Fixed a newly added or reconnected WireGuard gateway sometimes staying unrecognized, with no IP information and its pinned services blocked, until the server restarted. diff --git a/shared-libs/crates/start-core/Cargo.toml b/shared-libs/crates/start-core/Cargo.toml index 84aa5b5450..476b9de43e 100644 --- a/shared-libs/crates/start-core/Cargo.toml +++ b/shared-libs/crates/start-core/Cargo.toml @@ -274,6 +274,7 @@ serde_toml = { package = "toml", version = "0.9" } clap_mangen = "0.2.33" tempfile = "3.14.0" tokio = { version = "1.38.1", features = ["test-util"] } +zbus = { version = "5.1.1", features = ["p2p"] } [target.'cfg(target_os = "linux")'.dependencies] inotify = "0.11.0" diff --git a/shared-libs/crates/start-core/src/net/gateway.rs b/shared-libs/crates/start-core/src/net/gateway.rs index 8d071a2f2f..26607daa4f 100644 --- a/shared-libs/crates/start-core/src/net/gateway.rs +++ b/shared-libs/crates/start-core/src/net/gateway.rs @@ -7,6 +7,7 @@ use std::time::{Duration, Instant}; use chrono::Utc; use clap::Parser; +use futures::future::BoxFuture; use futures::{FutureExt, Stream, StreamExt, TryStreamExt}; use imbl::{OrdMap, OrdSet}; use imbl_value::{InternedString, Value}; @@ -19,7 +20,7 @@ use serde::{Deserialize, Serialize}; use tokio::io::{AsyncBufReadExt, BufReader}; use tokio::net::TcpListener; use tokio::process::Command; -use tokio::sync::oneshot; +use tokio::sync::{Notify, oneshot}; use url::Url; use visit_rs::{Visit, VisitFields}; use zbus::proxy::{PropertyChanged, PropertyStream, SignalStream}; @@ -1509,6 +1510,21 @@ impl<'a> StubStream<'a> for SignalStream<'a> { } } +/// Resolves once the device's `IpInterface` differs from the observed name. +/// +/// NetworkManager leaves `IpInterface` empty until activation reaches `IP_CHECK`, and announces +/// the name only on the device itself. A scan that skips an unnamed device depends on this to +/// rescan it. +async fn ip_interface_changed(device_proxy: &DeviceProxy<'_>, observed: &str) -> Result<(), Error> { + let mut changes = device_proxy.receive_ip_interface_changed().await; + while let Some(change) = changes.next().await { + if change.get().await? != observed { + return Ok(()); + } + } + futures::future::pending().await +} + #[instrument(skip_all)] async fn watcher( watch_ip_info: Watch>, @@ -1527,7 +1543,16 @@ async fn watcher( let netman_proxy = NetworkManagerProxy::new(&connection).await?; + let rescan = Notify::new(); + let rescan = &rescan; let mut until = Until::new() + .with_async_fn(move || { + async move { + rescan.notified().await; + Ok(()) + } + .fuse() + }) .with_stream(netman_proxy.receive_all_devices_changed().await.stub()) .with_stream( netman_proxy @@ -1563,13 +1588,21 @@ async fn watcher( ); let mut ifaces = BTreeSet::new(); let mut policy_ifaces: BTreeMap = BTreeMap::new(); - let mut jobs = Vec::new(); + let mut jobs: Vec<(String, BoxFuture<'_, Result<(), Error>>)> = Vec::new(); for device in devices { - use futures::future::Either; - let device_proxy = device::DeviceProxy::new(&connection, device.clone()).await?; let iface = InternedString::intern(device_proxy.ip_interface().await?); + jobs.push((device.to_string(), { + let device_proxy = device_proxy.clone(); + let observed = iface.clone(); + async move { + ip_interface_changed(&device_proxy, &observed).await?; + rescan.notify_one(); + Ok(()) + } + .boxed() + })); if iface.is_empty() { continue; } @@ -1588,25 +1621,27 @@ async fn watcher( } if watch_activation.peek(|a| a.contains_key(&iface)) { jobs.push(( - iface.clone(), - Either::Left(watch_activated( + iface.to_string(), + watch_activated( &connection, device_proxy.clone(), iface.clone(), &watch_activation, - )), + ) + .boxed(), )); } jobs.push(( - iface.clone(), - Either::Right(watch_ip( + iface.to_string(), + watch_ip( &connection, device_proxy.clone(), iface.clone(), &watch_ip_info, db.as_ref(), - )), + ) + .boxed(), )); ifaces.insert(iface); } @@ -3759,6 +3794,127 @@ mod policy_rule_tests { } } +#[cfg(test)] +mod ip_interface_tests { + use super::*; + + const DEVICE_PATH: &str = "/org/freedesktop/NetworkManager/Devices/7"; + + struct FakeDevice { + ip_interface: String, + } + + #[zbus::interface(name = "org.freedesktop.NetworkManager.Device")] + impl FakeDevice { + #[zbus(property)] + fn ip_interface(&self) -> String { + self.ip_interface.clone() + } + } + + /// A NetworkManager stand-in serving one device, and a client connected to it. + #[allow(deprecated)] + async fn fake_network_manager(ip_interface: &str) -> (Connection, Connection) { + let (server, client) = std::os::unix::net::UnixStream::pair().unwrap(); + let device = FakeDevice { + ip_interface: ip_interface.to_owned(), + }; + let (server, client) = tokio::join!( + async { + zbus::connection::Builder::unix_stream(server) + .server(zbus::Guid::generate()) + .unwrap() + .p2p() + .serve_at(DEVICE_PATH, device) + .unwrap() + .build() + .await + .unwrap() + }, + async { + zbus::connection::Builder::unix_stream(client) + .p2p() + .build() + .await + .unwrap() + }, + ); + (server, client) + } + + async fn rename(server: &Connection, ip_interface: &str) { + let device = server + .object_server() + .interface::<_, FakeDevice>(DEVICE_PATH) + .await + .unwrap(); + device.get_mut().await.ip_interface = ip_interface.to_owned(); + device + .get() + .await + .ip_interface_changed(device.signal_emitter()) + .await + .unwrap(); + } + + async fn observe(client: &Connection) -> (DeviceProxy<'_>, String) { + let device = DeviceProxy::new(client, DEVICE_PATH).await.unwrap(); + let observed = device.ip_interface().await.unwrap(); + (device, observed) + } + + #[tokio::test] + async fn an_unnamed_device_is_reported_once_it_gains_an_ip_interface() { + let (server, client) = fake_network_manager("").await; + let (device, observed) = observe(&client).await; + assert_eq!(observed, ""); + + let changed = ip_interface_changed(&device, &observed); + tokio::pin!(changed); + assert!( + tokio::time::timeout(Duration::from_millis(300), &mut changed) + .await + .is_err(), + "an unchanged interface must not trigger a rescan" + ); + + rename(&server, "wg1").await; + tokio::time::timeout(Duration::from_secs(5), changed) + .await + .expect("the new interface name must trigger a rescan") + .unwrap(); + } + + #[tokio::test] + async fn a_rename_before_the_wait_begins_is_not_lost() { + let (server, client) = fake_network_manager("").await; + let (device, observed) = observe(&client).await; + + rename(&server, "wg1").await; + tokio::time::timeout(Duration::from_secs(5), async { + while device + .inner() + .cached_property::("IpInterface") + .unwrap() + .as_deref() + != Some("wg1") + { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + + tokio::time::timeout( + Duration::from_secs(5), + ip_interface_changed(&device, &observed), + ) + .await + .expect("a rename the scan missed must trigger a rescan") + .unwrap(); + } +} + #[cfg(test)] mod lookup_tests { use super::*; From 21958a2a57401347108ddfeec08b76b90ddfd1c5 Mon Sep 17 00:00:00 2001 From: Victor Date: Thu, 19 Nov 2026 13:53:06 -0600 Subject: [PATCH 18/38] fix(start-os): carry out a restart or shutdown when a service fails to stop (#4736) When one service failed to tear down, RpcContext::shutdown returned the error before marking the context closed, and startd's inner_main returned it before the power action it had already received. main then started Diagnostic Mode instead of running Shutdown::execute, so the server never rebooted, and a waiting `start-cli server restart` hung because wait_closed never resolved. RpcContext::shutdown now logs the teardown error, always closes the context and returns nothing, so the requested restart or shutdown goes ahead. The logged error names the package whose teardown failed. Fixes #4638 Co-authored-by: Claude Fable 5.2 --- ...d-restart-after-failed-service-teardown.md | 5 +++ .../crates/start-core/src/bins/startd.rs | 2 +- .../crates/start-core/src/context/rpc.rs | 43 +++++++++++++++---- .../start-core/src/service/service_map.rs | 5 ++- 4 files changed, 43 insertions(+), 12 deletions(-) create mode 100644 projects/start-os/changelog/patch-fixed-restart-after-failed-service-teardown.md diff --git a/projects/start-os/changelog/patch-fixed-restart-after-failed-service-teardown.md b/projects/start-os/changelog/patch-fixed-restart-after-failed-service-teardown.md new file mode 100644 index 0000000000..fcd150c896 --- /dev/null +++ b/projects/start-os/changelog/patch-fixed-restart-after-failed-service-teardown.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Carry out a requested restart or shutdown when a service fails to stop cleanly, instead of entering Diagnostic Mode. diff --git a/shared-libs/crates/start-core/src/bins/startd.rs b/shared-libs/crates/start-core/src/bins/startd.rs index 90c8d2e71c..5e323da646 100644 --- a/shared-libs/crates/start-core/src/bins/startd.rs +++ b/shared-libs/crates/start-core/src/bins/startd.rs @@ -145,7 +145,7 @@ async fn inner_main( Ok::<_, Error>((rpc_ctx, shutdown)) } .await?; - rpc_ctx.shutdown().await?; + rpc_ctx.shutdown().await; Ok(shutdown) } diff --git a/shared-libs/crates/start-core/src/context/rpc.rs b/shared-libs/crates/start-core/src/context/rpc.rs index 47c6932cdb..a40e784643 100644 --- a/shared-libs/crates/start-core/src/context/rpc.rs +++ b/shared-libs/crates/start-core/src/context/rpc.rs @@ -97,6 +97,16 @@ impl Drop for RpcContextSeed { } } +async fn close_after_teardown( + teardown: impl Future>, + is_closed: &AtomicBool, + closed: &watch::Sender, +) { + teardown.await.log_err(); + is_closed.store(true, Ordering::SeqCst); + closed.send_replace(true); +} + pub struct Hardware { pub devices: Vec, pub ram: u64, @@ -595,19 +605,18 @@ impl RpcContext { } #[instrument(skip_all)] - pub async fn shutdown(self) -> Result<(), Error> { + pub async fn shutdown(self) { self.crons.mutate(|c| std::mem::take(c)); - self.services.shutdown_all().await?; - self.is_closed.store(true, Ordering::SeqCst); - self.closed.send_replace(true); + close_after_teardown( + self.services.shutdown_all(), + &self.0.is_closed, + &self.0.closed, + ) + .await; tracing::info!("{}", t!("context.rpc.rpc-context-shutdown")); - Ok(()) } - /// Resolves once graceful teardown (`shutdown`) has completed. Used by the - /// `wait` path of the server shutdown/restart RPC so a caller can block - /// until containers are stopped (it won't outlive the webserver teardown - /// that immediately follows). + /// Resolves once service teardown has finished, failed or not. pub async fn wait_closed(&self) { let mut rx = self.0.closed.subscribe(); let _ = rx.wait_for(|closed| *closed).await; @@ -824,6 +833,22 @@ mod tests { } } + #[tokio::test] + async fn failed_teardown_still_closes_the_context() { + let is_closed = AtomicBool::new(false); + let closed = watch::Sender::new(false); + + close_after_teardown( + async { Err(Error::new(eyre!("teardown failed"), ErrorKind::Unknown)) }, + &is_closed, + &closed, + ) + .await; + + assert!(is_closed.load(Ordering::SeqCst)); + assert!(*closed.borrow()); + } + #[tokio::test] async fn reloadable_http_client_replaces_future_clones() { let proxy = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); diff --git a/shared-libs/crates/start-core/src/service/service_map.rs b/shared-libs/crates/start-core/src/service/service_map.rs index 829dc647b7..cc51d0d4fb 100644 --- a/shared-libs/crates/start-core/src/service/service_map.rs +++ b/shared-libs/crates/start-core/src/service/service_map.rs @@ -522,10 +522,11 @@ impl ServiceMap { pub async fn shutdown_all(&self) -> Result<(), Error> { let futs = self.0.mutate(|lock| { let mut futs = Vec::with_capacity(lock.len()); - for service in lock.values().cloned() { + for (id, service) in lock.iter() { + let (id, service) = (id.clone(), service.clone()); futs.push(async move { if let Some(service) = service.write_owned().await.take() { - service.shutdown(None).await? + service.shutdown(None).await.with_ctx(|e| (e.kind, &id))? } Ok::<_, Error>(()) }); From e8c4648239f18ea224841d7b3f79c403824b94c1 Mon Sep 17 00:00:00 2001 From: "start9-docs-bot[bot]" <315476469+start9-docs-bot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:59:17 +0000 Subject: [PATCH 19/38] docs: backport live-docs d476b3788 to master Backports the following from live-docs: - d476b3788 docs(sdk): state the merge method for package PRs in agent context (#4809) --- projects/start-sdk/docs/src/agent-context.md | 1 + 1 file changed, 1 insertion(+) diff --git a/projects/start-sdk/docs/src/agent-context.md b/projects/start-sdk/docs/src/agent-context.md index fd0ff0cee2..50319fafbc 100644 --- a/projects/start-sdk/docs/src/agent-context.md +++ b/projects/start-sdk/docs/src/agent-context.md @@ -132,6 +132,7 @@ The full rules are in `start-technologies/projects/start-sdk/docs/src/workflow.m - **Keep `README.md` and `instructions.md` in sync.** `README.md` is the package's technical reference — how it works, what its actions do, how to diagnose it — and the only technical file an AI support or administering agent reads; `instructions.md` is the user's guide to the service as it is now — never a record of what changed, which belongs in `releaseNotes`. Update each in the same change as the code that makes it wrong. Content rules: `writing-readmes.md`, `writing-instructions.md`. - **A package's `AGENTS.md` restates nothing `README.md` or `instructions.md` says.** Its one reader has both, so it carries only what has no home in them: repo mechanics, a change that looks right and is not (the imperative plus the one clause that says why), extension points, naming traps, and build or test invocations particular to the repo. A fact the README already states does not become a rule by being repeated here. Most packages need one to four bullets; a simple one needs none. (`project-structure.md` § AGENTS.md and CLAUDE.md) - **Iterate with a dirty tree; commit once.** The `-modified` pack-hash suffix is informational — don't commit between test attempts. One clean commit when the package works; `git reset --soft HEAD~N` collapses accumulated fixups. +- **Squash a feature branch's PR; give a long-lived branch's PR a merge commit.** `next`, a release line and a `sync-next/` branch take `gh pr merge --merge`, or the next sync conflicts with commits the base already holds in squashed form. (`maintaining-a-package.md` § Merge a long-lived branch with a merge commit, never a squash) - **Bump to the latest SDK before opening a PR.** Check `npm view @start9labs/start-sdk version` against the pin; if newer, bump and re-verify before you push. (`publishing.md` § Pre-Publish Checklist, `maintaining-a-package.md` § Bumping the SDK) - **Pre-existing errors are still errors.** A red `tsc`, test, or pack step means the package doesn't pass, even if unrelated to your change. Fix it or flag it; never report green when a check was red. - **Don't create unnecessary version files.** The latest version always lives in `startos/versions/current.ts`; most bumps just edit that file in place. A new file is spun off only when the version already in `current.ts` carries a migration, meaning an `up` whose body does work (the template's empty `up` with `down: IMPOSSIBLE` carries none). That migration stays with the version that introduced it and is never carried forward into a successor, idempotent or not, while **a version having been released is not a reason to declare it.** `VersionGraph` synthesizes a range vertex beneath `current`, so any lower installed version migrates up in one hop without its own node; `canMigrateFrom` is derived from that graph, not authored. See `versions.md` (When to Create a New Version File, Why Released Versions Don't Need to Be Declared, Release Notes). From dc3c66674af8c9f7705395c01740eaf22087b471 Mon Sep 17 00:00:00 2001 From: Helix the Red <355572797+helix-red@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:46:33 -0700 Subject: [PATCH 20/38] fix(storage): present shared CIFS volumes as nobody in every container (#4810) Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --- projects/start-sdk/docs/src/shared-volumes.md | 2 +- shared-libs/crates/start-core/ARCHITECTURE.md | 4 ++-- .../crates/start-core/src/disk/mount/filesystem/cifs.rs | 5 +++-- shared-libs/crates/start-core/src/shared_volumes/source.rs | 2 +- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/projects/start-sdk/docs/src/shared-volumes.md b/projects/start-sdk/docs/src/shared-volumes.md index a95d055ae5..c38f78cc1c 100644 --- a/projects/start-sdk/docs/src/shared-volumes.md +++ b/projects/start-sdk/docs/src/shared-volumes.md @@ -20,7 +20,7 @@ This enables the service's **Shared Volumes** controls in StartOS; it requests n const grants = await sdk.getSharedVolumes(effects).const() ``` -Each grant contains `id`, `name`, `readonly` and `availability`. Store the stable GUID `id` in service configuration and use the editable `name` in user-facing choices. Names are neither identities nor paths. The catalog returns neither host paths nor network credentials. Local and attached-drive mounts use the same service UID/GID mapping as package-owned volumes; attaching does not rewrite their on-disk owners. Linux mount metadata can reveal the CIFS account name to a granted service; its password remains private. +Each grant contains `id`, `name`, `readonly` and `availability`. Store the stable GUID `id` in service configuration and use the editable `name` in user-facing choices. Names are neither identities nor paths. The catalog returns neither host paths nor network credentials. Local and attached-drive mounts use the same service UID/GID mapping as package-owned volumes; attaching does not rewrite their on-disk owners. A CIFS volume's files appear owned by `nobody`, with mode `0666` for files and `0777` for directories. A service can read, write and create files there but cannot change their owner or mode. Linux mount metadata can reveal the CIFS account name to a granted service; its password remains private. The reader supports `.once()`, `.const()`, `.watch()` and the other [reactive reader methods](file-models.md). Reactive reads are invalidated only when one of the service's own granted volumes changes in a way its mounts depend on: a grant is added or revoked, its access mode changes, it becomes available or unavailable (a status reset to unknown does not count), or its source changes, including updated CIFS connection details. Renames and changes to other volumes do not invalidate them, so a returned name can be stale until the next read. Updating a CIFS share's connection details does not change an existing mount, which keeps the source it opened until the service mounts the volume again. An offline granted volume remains listed; revocation removes it. Availability is the host's last observation, not a mount preflight or a guarantee of continued connectivity. diff --git a/shared-libs/crates/start-core/ARCHITECTURE.md b/shared-libs/crates/start-core/ARCHITECTURE.md index 5af1d91ab9..1aa096ab9c 100644 --- a/shared-libs/crates/start-core/ARCHITECTURE.md +++ b/shared-libs/crates/start-core/ARCHITECTURE.md @@ -35,7 +35,7 @@ how `startbox` dispatches to `startd`, `start-cli`, etc. The per-entrypoint logi - `src/net/` — Networking (DNS, ACME, WiFi, Tor, WireGuard, gateway/NAT) - `src/net/static_server.rs` — UI and authenticated archive/icon resources. Resource signatures reuse `SignatureAuthorizationContext::check_pubkey` for enrollment. The registry-icon proxy signs exact content-addressed icon URLs under saved registries with the server identity key, using the shared icon path validator and canonical registry enumeration. Signed upstream GETs refuse redirects; other images and archive download hosts retain their existing transport policy. Upstream status, content type and cache policy pass through; unrelated response headers do not. - `src/s9pk/` — S9PK package format (merkle archive) -- `src/lxc/` — LXC container management for packages. `filesystem::service_filesystem` owns base UID/GID mapping and package-remap composition for package volumes, runtime rootfs, assets, images and backup views. Shared local and disk volumes are mounted on the host without an idmap; attaching one into a container applies the base map. CIFS supplies service ownership through mount options; host-only staging and backup targets retain raw filesystem views. +- `src/lxc/` — LXC container management for packages. `filesystem::service_filesystem` owns base UID/GID mapping and package-remap composition for package volumes, runtime rootfs, assets, images and backup views. Shared local and disk volumes are mounted on the host without an idmap; attaching one into a container applies the base map. CIFS cannot be idmapped; its shared mount is owned by host root with world-writable modes, so every container sees `nobody` and none can change owners or modes; host-only staging and backup targets retain raw filesystem views. - `src/install/`, `src/update/` — Package install and OS/package update flows - `src/trusted_keys.rs` — Individual signing-key trust (`TrustedKey.publicKey`), immutable import provenance, committed initial certificates in `src/trusted_keys/initial/`, and legacy OS-signer adapters. `src/trusted_keys/legacy.rs` owns historical grouped-keyring decoding and migration to canonical per-key records; downgrade restores the historical array shape. `src/trusted_keys/connection.rs` atomically records registry connections and advertised-key snapshots. Connecting trusts keys new to the server for packages. Registry index synchronization imports newly listed keys disabled, preserves existing trust and provenance, and issues a `RegistryKeyAdded` notification for each key new to the server and a `RegistryKeyDropped` notification for each key the registry stops offering. Selecting the StartOS update registry trusts its listed keys for OS updates, and that registry cannot be removed. Connected registry listings determine deletion protection, and the last OS-update key cannot lose its trust. `src/sign/gpg.rs` retains original exports and attributes self-certified identities and OpenPGP fingerprints to each signing key. - `src/update/signer_files.rs` — Mirrors OS-update trust to PEM files in the config overlay at `/etc/startos/os-signers`, reconciled from the database during RPC initialization after database migrations. Trust-changing RPCs serialize database mutations and await filesystem persistence. Diagnostic updates read that selection without the data drive, falling back to the image's three production keys only before a selection has been saved. Regular `LocalAuth` verifies its protected cookie, strips caller-supplied `__Auth_local` claims, and injects its authentication result when `get_local_auth` metadata requests it. The diagnostic update endpoint uses that injected result to authorize trust overrides. @@ -143,7 +143,7 @@ See [patchdb.md](patchdb.md) for `TypedDbWatch` construction, API, and usage `Public.backupTargets` owns registered local-folder, external-folder and CIFS destinations. Runtime backup/restore/conversion methods resolve these IDs; setup retains its inline recovery-source contract. Attached drives register through source creation or explicit `backup.target.find`. Find reuses disk discovery and shared source preparation to register partition roots with recognized `StartOSBackupsV2` metadata, without recursive folder discovery or modifying backup contents. Background inventory scans never register targets. The catalog atomically skips already registered filesystem-UUID/root pairs, retaining names and settings; a removed target can be rediscovered with a fresh identity. Boot consumes the historical private CIFS catalog into targets and password-only private credentials, preserving existing CIFS IDs. New IDs are GUIDs independent of connection details. Managed local shared volumes and targets are Btrfs subvolumes beneath the persistent `PACKAGE_DATA` partition at `shared-volumes/` and `backup-targets/`. `DATA_DIR` itself is a volatile mount scaffold. Their path owners also supply generated `managedStorage` directories for clients; the UI presents names rather than opaque catalog IDs or internal managed paths. Migration consumes the legacy private CIFS catalog; rollback to an older same-version development build without registered-target support is unsupported. -`backup::target::catalog` reuses shared source preparation and inspection DTOs. `PreparedFilesystem` shares managed-subvolume validation and filesystem delegation; concrete filesystem types preserve shared-CIFS service ownership and raw host storage policy. Shared-volume backups copy that single host view, holding container ids like package backups; a CIFS backup, whose view carries only the forced service owner, is owned by root. Restores copy them back unchanged. `PinnedDirectory` owns confined descriptor opening and its stable path. Prepared callers retain their backing mount; observer reads retain the directory descriptor without mount-cache ownership. Managed local removal reserves the existing mount-cache slot, rejects active users and excludes new mounts through committed subvolume deletion, including nested subvolume roots. Shared-volume removal revokes future authorization and retires managed staging sources before deleting local data. Registration survives failed or interrupted deletion for retry; successful deletion unregisters the source. The Btrfs cleaner reclaims the removed subvolume's space asynchronously. Boot converts ordinary local roots with the package-volume reflink/swap recovery owner before observers or services start. Local shared roots carrying the legacy LXC ownership offset are replaced through the inverse ownership view and the same recoverable reflink/swap owner, independently of version-keyed migrations; backup targets retain raw owners. Obsolete pending local deletions recover as named, ungranted registrations during database normalization. External removal preserves contents. Observations reject stale source/credential snapshots and never recreate removed records. Backup, conversion and legacy-cleanup completion refresh target recovery metadata. Legacy CIFS add/update validate the share and existing unencrypted backup metadata before publishing a change; the target lifecycle RPCs retain unavailable configuration intent. Both reuse the target-content inspection owner, where capacity failures are diagnostic rather than a mount or metadata-validation failure. Mounted targets use the same metadata reader for initialization and recovery without opening another mount. The catalog requires validated contents before an unknown or unavailable target becomes available; folder-only status updates cannot clear metadata errors. The backup terminal-report owner persists completed background runs in private history with the target name captured at acceptance; `backup.history.list` pages them newest first. Synchronous request/setup rejection does not create a completed background run. +`backup::target::catalog` reuses shared source preparation and inspection DTOs. `PreparedFilesystem` shares managed-subvolume validation and filesystem delegation; concrete filesystem types preserve the root-owned shared-CIFS view and raw host storage policy. Shared-volume backups copy that single host view, holding container ids like package backups; a CIFS backup is owned by root. Restores copy them back unchanged. `PinnedDirectory` owns confined descriptor opening and its stable path. Prepared callers retain their backing mount; observer reads retain the directory descriptor without mount-cache ownership. Managed local removal reserves the existing mount-cache slot, rejects active users and excludes new mounts through committed subvolume deletion, including nested subvolume roots. Shared-volume removal revokes future authorization and retires managed staging sources before deleting local data. Registration survives failed or interrupted deletion for retry; successful deletion unregisters the source. The Btrfs cleaner reclaims the removed subvolume's space asynchronously. Boot converts ordinary local roots with the package-volume reflink/swap recovery owner before observers or services start. Local shared roots carrying the legacy LXC ownership offset are replaced through the inverse ownership view and the same recoverable reflink/swap owner, independently of version-keyed migrations; backup targets retain raw owners. Obsolete pending local deletions recover as named, ungranted registrations during database normalization. External removal preserves contents. Observations reject stale source/credential snapshots and never recreate removed records. Backup, conversion and legacy-cleanup completion refresh target recovery metadata. Legacy CIFS add/update validate the share and existing unencrypted backup metadata before publishing a change; the target lifecycle RPCs retain unavailable configuration intent. Both reuse the target-content inspection owner, where capacity failures are diagnostic rather than a mount or metadata-validation failure. Mounted targets use the same metadata reader for initialization and recovery without opening another mount. The catalog requires validated contents before an unknown or unavailable target becomes available; folder-only status updates cannot clear metadata errors. The backup terminal-report owner persists completed background runs in private history with the target name captured at acceptance; `backup.history.list` pages them newest first. Synchronous request/setup rejection does not create a completed background run. Backup-FS mount caching and trash sweeps use actual directory identity, including through pinned descriptors and aliases; a replacement at the same pathname does not reuse an old encrypted mount. Public source errors redact private cache identities. diff --git a/shared-libs/crates/start-core/src/disk/mount/filesystem/cifs.rs b/shared-libs/crates/start-core/src/disk/mount/filesystem/cifs.rs index dd68bc7073..3788f92e33 100644 --- a/shared-libs/crates/start-core/src/disk/mount/filesystem/cifs.rs +++ b/shared-libs/crates/start-core/src/disk/mount/filesystem/cifs.rs @@ -268,7 +268,7 @@ mod tests { .await .unwrap() .uid(), - 100000 + 0 ); let mut guest = definition("127.0.0.1", "/guest"); guest.0.username.clear(); @@ -699,6 +699,7 @@ impl FileSystem for Cifs { } /// CIFS lacks `FS_ALLOW_IDMAP`; service ownership comes from mount options. +/// Owned by host root with world-writable modes; containers see `nobody` and cannot change owners or modes. pub struct SharedCifs(pub Cifs); impl FileSystem for SharedCifs { @@ -709,7 +710,7 @@ impl FileSystem for SharedCifs { ) -> Result<(), Error> { tokio::time::timeout(std::time::Duration::from_secs(30), self.0.mount_with_options( mountpoint.as_ref(), - &format!("vers=3,soft,echo_interval=5,noserverino,uid={0},gid={0},forceuid,forcegid,file_mode=0666,dir_mode=0777,{1}", crate::lxc::BASE_IDMAP.to_id, access_options(mount_type)), + &format!("vers=3,soft,echo_interval=5,noserverino,uid=0,gid=0,forceuid,forcegid,file_mode=0666,dir_mode=0777,{}", access_options(mount_type)), )).await.map_err(|error| Error::new(error, crate::ErrorKind::Timeout))? } diff --git a/shared-libs/crates/start-core/src/shared_volumes/source.rs b/shared-libs/crates/start-core/src/shared_volumes/source.rs index 4a5f88e275..83aa3c93b6 100644 --- a/shared-libs/crates/start-core/src/shared_volumes/source.rs +++ b/shared-libs/crates/start-core/src/shared_volumes/source.rs @@ -159,7 +159,7 @@ pub(crate) enum PreparedFilesystem { Cifs(C), } /// Host views carry no idmap: local and disk files keep container ids, which attachment maps. -/// CIFS cannot be idmapped and presents its forced service owner instead. +/// CIFS cannot be idmapped and presents host root, `nobody` inside every container. pub(crate) type SourceFilesystem = PreparedFilesystem, SharedCifs>; impl SourceFilesystem { From bbbfed0a7d3b7ee6e5d1ba32f921bdf720179420 Mon Sep 17 00:00:00 2001 From: Dominion5254 Date: Thu, 19 Nov 2026 16:04:05 -0700 Subject: [PATCH 21/38] feat(start-wrt): factory reset from the FDL button (#4519) * feat(start-wrt): factory reset from the FDL button The FDL button sits on QSPI_DATA3, a boot strap the BootROM samples only as the chip leaves reset. Declare it to the kernel's built-in gpio-keys driver and watch the input device from a procd service, `startwrt startwrt-fdl-reset`, for the life of the system. A press held for 10 seconds blinks sys-led, and the release wipes the overlay and reboots. Acting on release keeps the strap low across the reboot, so a completed hold cannot land in download mode. The service asks the kernel for the key state on startup, so a hold started before it runs counts. It runs as its own respawned process, so it works when the daemon does not. The device tree is a plain target dts that includes the vendor k1-x_deb1.dts, rather than a kernel patch, and keeps its name for the boot firmware. gpio-button-hotplug and rc.button are not used: they need broadcast_uevent, an OpenWrt kernel hack absent from the K1's 6.18 kernel. * fix(start-wrt): reject stale FDL hold histories Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol --------- Co-authored-by: helix-white <267227783+helix-a@users.noreply.github.com> --- Cargo.lock | 2 +- projects/start-wrt/backend/ARCHITECTURE.md | 3 +- projects/start-wrt/backend/ctrl/Cargo.toml | 5 +- .../backend/ctrl/src/bin/startwrt.rs | 1 + .../backend/ctrl/src/bins/fdl_reset.rs | 18 + .../start-wrt/backend/ctrl/src/bins/mod.rs | 6 + .../start-wrt/backend/ctrl/src/fdl_button.rs | 326 ++++++++++++++++++ projects/start-wrt/backend/ctrl/src/lib.rs | 1 + projects/start-wrt/backend/ctrl/src/system.rs | 31 +- projects/start-wrt/build/stage-files.sh | 18 + .../minor-added-fdl-factory-reset.md | 5 + projects/start-wrt/docs/src/factory-reset.md | 19 +- projects/start-wrt/docs/src/faq.md | 2 +- .../target/linux/spacemit/dts/k1-x_deb1.dts | 28 ++ .../target/linux/spacemit/image/k1-sbc.mk | 2 +- 15 files changed, 455 insertions(+), 12 deletions(-) create mode 100644 projects/start-wrt/backend/ctrl/src/bins/fdl_reset.rs create mode 100644 projects/start-wrt/backend/ctrl/src/fdl_button.rs create mode 100644 projects/start-wrt/changelog/minor-added-fdl-factory-reset.md create mode 100644 projects/start-wrt/openwrt-overlay/target/linux/spacemit/dts/k1-x_deb1.dts diff --git a/Cargo.lock b/Cargo.lock index b889133cff..5e52158b18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8591,7 +8591,7 @@ dependencies = [ [[package]] name = "startwrt-core" -version = "1.4.1" +version = "1.5.0" dependencies = [ "async_cell", "axum", diff --git a/projects/start-wrt/backend/ARCHITECTURE.md b/projects/start-wrt/backend/ARCHITECTURE.md index db47137f2d..54fdb9c3e4 100644 --- a/projects/start-wrt/backend/ARCHITECTURE.md +++ b/projects/start-wrt/backend/ARCHITECTURE.md @@ -38,7 +38,7 @@ pub trait CtrlContext: Context + Clone { - **`ServerContext`**: always reads `/etc/config/`, always reloads services. Holds `start-core`'s `RpcContinuations` for long-running operations and the auth state (enrolled keys, nonce cache). `ServerContext::default()` carries an in-memory auth state that enrolls nothing; only the daemon opens `/etc/startwrt/auth.db`. The daemon loads its separate server identity from `serverIdentityKey` in `/etc/startwrt/auth.db` through `start-core`'s instance-key loader; sysupgrade keeps that database. In-memory contexts generate an ephemeral server identity. The daemon-local setup flash gate is shared by typed RPC and legacy NDJSON. Its owned mutex guard stays with accepted work on start-core's `make_send` runtime; observer cancellation cannot release it or abort provisioning. Actual worker results supply typed terminals or legacy Complete/Error events. Shared blocking work participates in the daemon's existing 60-second runtime shutdown grace; forced termination or reboot can still interrupt writes. Optional immutable `SecureSession` provenance belongs to each context clone rather than the shared auth state; WebSocket continuation creators capture it independently of revocation and resource policy. - **`CliContext`**: configurable root (`--config-root`), calls the daemon when needed. The identity at `~/.startwrt/id.key.pem` signs a fresh ephemeral-DH hello through the shared opaque signer before transport deadlines. Local tokens take precedence, restricted to loopback hosts; token and missing-key calls use the existing SessionClient's unpersisted proof identity without enrollment. Malformed keys fail closed. The ordinary HTTP client retains its network policy; an HTTP/1-only, nonredirecting upgrade client uses the shared encrypted transport. Login retry and command output stay in the CLI owner. Log/update commands return their existing GUID values rather than consuming the streams; browser continuation owners redeem secure-origin GUIDs through fresh same-peer exchanges. -The single binary `startwrt` uses `MultiExecutable` to dispatch based on the symlink name (`startwrt-ctrld` or `startwrt-cli`) or the first argument. +The single binary `startwrt` uses `MultiExecutable` to dispatch based on the symlink name (`startwrt-ctrld`, `startwrt-cli`, or `startwrt-fdl-reset`) or the first argument. ### CLI Arguments @@ -227,6 +227,7 @@ Low-level UCI, file, and shell access. These are vestigial — all features now | `sign/` | ed25519 signature + commitment verification | | `progress.rs` | Progress reporting, wire-compatible with start-os | | `eeprom.rs` | EEPROM TLV read (ONIE blob; WiFi PMK in tag 0x2F) | +| `fdl_button.rs` | Factory reset from the FDL button, watched for the life of the system; runs as `startwrt startwrt-fdl-reset` | | `wg.rs` | WireGuard key management types | | `device_names.rs` | Persistent cache of auto-learned device hostnames | | `verify.rs` | Factory QC checks (firmware integrity, EEPROM password, SSID broadcast) | diff --git a/projects/start-wrt/backend/ctrl/Cargo.toml b/projects/start-wrt/backend/ctrl/Cargo.toml index 3a89c9b565..977436de61 100644 --- a/projects/start-wrt/backend/ctrl/Cargo.toml +++ b/projects/start-wrt/backend/ctrl/Cargo.toml @@ -2,7 +2,7 @@ edition = "2021" license = "MIT" name = "startwrt-core" -version = "1.4.1" # VERSION_BUMP +version = "1.5.0" # VERSION_BUMP [lib] name = "startwrt" @@ -47,9 +47,12 @@ macaddr = "1.0.0" mime_guess = "2" nix = { version = "0.29.0", features = [ "fs", + "ioctl", "net", + "poll", "signal", "socket", + "time", "uio", ] } num_enum = "0.7" diff --git a/projects/start-wrt/backend/ctrl/src/bin/startwrt.rs b/projects/start-wrt/backend/ctrl/src/bin/startwrt.rs index 79c2a64306..109980d9d4 100644 --- a/projects/start-wrt/backend/ctrl/src/bin/startwrt.rs +++ b/projects/start-wrt/backend/ctrl/src/bin/startwrt.rs @@ -4,6 +4,7 @@ fn main() { MultiExecutable::default() .enable_daemon() .enable_cli() + .enable_fdl_reset() .set_default("startwrt-cli") .execute() } diff --git a/projects/start-wrt/backend/ctrl/src/bins/fdl_reset.rs b/projects/start-wrt/backend/ctrl/src/bins/fdl_reset.rs new file mode 100644 index 0000000000..0391e98436 --- /dev/null +++ b/projects/start-wrt/backend/ctrl/src/bins/fdl_reset.rs @@ -0,0 +1,18 @@ +use std::collections::VecDeque; +use std::ffi::OsString; + +use crate::{fdl_button, init_logging}; + +pub fn main(_args: VecDeque) { + init_logging("startwrt-fdl-reset"); + let result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("failed to build tokio runtime") + .block_on(fdl_button::watch()); + if let Err(e) = result { + fdl_button::restore_status_led(); + tracing::error!("FDL button: {e}"); + std::process::exit(1); + } +} diff --git a/projects/start-wrt/backend/ctrl/src/bins/mod.rs b/projects/start-wrt/backend/ctrl/src/bins/mod.rs index 960ef3efbd..80e48c67c3 100644 --- a/projects/start-wrt/backend/ctrl/src/bins/mod.rs +++ b/projects/start-wrt/backend/ctrl/src/bins/mod.rs @@ -1,5 +1,6 @@ pub mod cli; pub mod daemon; +pub mod fdl_reset; use std::collections::{HashMap, VecDeque}; use std::ffi::OsString; @@ -32,6 +33,11 @@ impl MultiExecutable { self } + pub fn enable_fdl_reset(&mut self) -> &mut Self { + self.handlers.insert("startwrt-fdl-reset", fdl_reset::main); + self + } + pub fn set_default(&mut self, name: &'static str) -> &mut Self { self.default = Some(name); self diff --git a/projects/start-wrt/backend/ctrl/src/fdl_button.rs b/projects/start-wrt/backend/ctrl/src/fdl_button.rs new file mode 100644 index 0000000000..54b9d17456 --- /dev/null +++ b/projects/start-wrt/backend/ctrl/src/fdl_button.rs @@ -0,0 +1,326 @@ +//! Factory reset from the FDL button. +//! +//! The kernel's `gpio-keys` driver reports the button as an input device. A +//! press held for [`HOLD`] blinks the status LED. The release wipes the overlay +//! and reboots, keeping the BootROM's download strap low across the reset. +//! Releasing before the LED cue cancels, even when the event is processed late. +//! Lost input history cancels the hold; procd restarts observation from live key state. + +use std::fs::{self, File}; +use std::io::Read; +use std::os::fd::{AsFd, AsRawFd}; +use std::path::PathBuf; +use std::time::Duration; + +use nix::poll::{poll, PollFd, PollFlags, PollTimeout}; +use nix::time::{clock_gettime, ClockId}; + +use crate::prelude::*; + +const HOLD: Duration = Duration::from_secs(10); + +const INPUT_DEVICE_NAME: &str = "gpio-keys"; +const STATUS_LED: &str = "/sys/class/leds/sys-led"; + +const EV_SYN: u16 = 0x00; +const EV_KEY: u16 = 0x01; +const SYN_DROPPED: u16 = 0x03; +const KEY_RESTART: u16 = 0x198; +const KEY_STATE_BYTES: usize = 0x300 / 8; +const EVENT_SIZE: usize = std::mem::size_of::(); +const EVENT_TYPE_OFFSET: usize = EVENT_SIZE - 8; +const EVENT_TIME_WORD_SIZE: usize = std::mem::size_of::(); + +nix::ioctl_read_buf!(eviocgkey, b'E', 0x18, u8); +nix::ioctl_write_ptr!(eviocsclockid, b'E', 0xa0, libc::c_int); + +#[derive(Debug, PartialEq, Eq)] +enum Action { + Wait(Option), + Blink, + Wipe, +} + +#[derive(Default)] +struct Button { + held_since: Option, + armed_at: Option, +} + +impl Button { + fn key(&mut self, pressed: bool, at: Duration) { + if !pressed { + if self.armed_at.is_some_and(|armed| at < armed) { + self.armed_at = None; + } + self.held_since = None; + } else if self.held_since.is_none() { + self.held_since = Some(at); + } + } + + fn blinked(&mut self, at: Duration) { + self.armed_at = Some(at); + } + + fn step(&self, now: Duration) -> Action { + match (self.armed_at, self.held_since) { + (Some(_), None) => Action::Wipe, + (Some(_), Some(_)) | (None, None) => Action::Wait(None), + (None, Some(since)) if now >= since + HOLD => Action::Blink, + (None, Some(since)) => Action::Wait(Some(since + HOLD - now)), + } + } +} + +fn find_device() -> Result, Error> { + for entry in fs::read_dir("/sys/class/input").with_kind(ErrorKind::Filesystem)? { + let entry = entry.with_kind(ErrorKind::Filesystem)?; + let event = entry.file_name(); + let Some(event) = event.to_str().filter(|n| n.starts_with("event")) else { + continue; + }; + let name = fs::read_to_string(entry.path().join("device/name")).unwrap_or_default(); + if name.trim() == INPUT_DEVICE_NAME { + return Ok(Some(PathBuf::from("/dev/input").join(event))); + } + } + Ok(None) +} + +fn monotonic_now() -> Result { + clock_gettime(ClockId::CLOCK_MONOTONIC) + .map(Duration::from) + .with_kind(ErrorKind::Filesystem) +} + +fn set_event_clock(device: &File) -> Result<(), Error> { + let clock = libc::CLOCK_MONOTONIC; + // SAFETY: `clock` is a live integer of the size the ioctl expects. + unsafe { eviocsclockid(device.as_raw_fd(), &clock) }.with_kind(ErrorKind::Filesystem)?; + Ok(()) +} + +fn key_is_down(device: &File) -> Result { + let mut state = [0u8; KEY_STATE_BYTES]; + // SAFETY: `state` is a live buffer whose length the ioctl receives. + unsafe { eviocgkey(device.as_raw_fd(), &mut state) }.with_kind(ErrorKind::Filesystem)?; + Ok(state[usize::from(KEY_RESTART) / 8] & (1 << (KEY_RESTART % 8)) != 0) +} + +fn parse_key_event(event: &[u8; EVENT_SIZE]) -> Result, Error> { + let field = |offset: usize| u16::from_ne_bytes([event[offset], event[offset + 1]]); + let kind = field(EVENT_TYPE_OFFSET); + let code = field(EVENT_TYPE_OFFSET + 2); + if kind == EV_SYN && code == SYN_DROPPED { + return Err(Error::other("FDL input queue overflow; hold history lost")); + } + if kind != EV_KEY || code != KEY_RESTART { + return Ok(None); + } + let seconds = libc::c_ulong::from_ne_bytes(event[..EVENT_TIME_WORD_SIZE].try_into().unwrap()); + let micros = libc::c_ulong::from_ne_bytes( + event[EVENT_TIME_WORD_SIZE..EVENT_TIME_WORD_SIZE * 2] + .try_into() + .unwrap(), + ); + let at = Duration::from_secs(seconds as u64) + Duration::from_micros(micros as u64); + let value = i32::from_ne_bytes([ + event[EVENT_TYPE_OFFSET + 4], + event[EVENT_TYPE_OFFSET + 5], + event[EVENT_TYPE_OFFSET + 6], + event[EVENT_TYPE_OFFSET + 7], + ]); + Ok(Some((value != 0, at))) +} + +fn set_status_led_attribute(attr: &str, value: &str) { + if let Err(e) = fs::write(format!("{STATUS_LED}/{attr}"), value) { + tracing::warn!("failed to set status LED {attr}: {e}"); + } +} + +pub(crate) fn restore_status_led() { + set_status_led_attribute("trigger", "heartbeat"); +} + +fn blink_status_led() { + for (attr, value) in [ + ("trigger", "timer"), + ("delay_on", "100"), + ("delay_off", "100"), + ] { + set_status_led_attribute(attr, value); + } +} + +/// Watches the button for the life of the system; a completed hold wipes the overlay and reboots. +pub async fn watch() -> Result<(), Error> { + let Some(path) = find_device()? else { + tracing::warn!("no {INPUT_DEVICE_NAME} input device"); + return Ok(()); + }; + restore_status_led(); + let mut device = File::open(path).with_kind(ErrorKind::Filesystem)?; + set_event_clock(&device)?; + let mut button = Button::default(); + button.key(key_is_down(&device)?, monotonic_now()?); + + loop { + let timeout = match button.step(monotonic_now()?) { + Action::Wipe => return crate::system::wipe_overlay_and_reboot().await, + Action::Blink => { + blink_status_led(); + button.blinked(monotonic_now()?); + continue; + } + Action::Wait(None) => PollTimeout::NONE, + Action::Wait(Some(wait)) => PollTimeout::try_from(wait.max(Duration::from_millis(1))) + .unwrap_or(PollTimeout::MAX), + }; + + let mut fds = [PollFd::new(device.as_fd(), PollFlags::POLLIN)]; + if poll(&mut fds, timeout).with_kind(ErrorKind::Filesystem)? > 0 { + let mut event = [0u8; EVENT_SIZE]; + device + .read_exact(&mut event) + .with_kind(ErrorKind::Filesystem)?; + if let Some((pressed, at)) = parse_key_event(&event)? { + let was_armed = button.armed_at.is_some(); + button.key(pressed, at); + if was_armed && button.armed_at.is_none() { + restore_status_led(); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const fn secs(s: u64) -> Duration { + Duration::from_secs(s) + } + + #[test] + fn idle_button_waits_without_a_deadline() { + let button = Button::default(); + assert_eq!(button.step(secs(0)), Action::Wait(None)); + assert_eq!(button.step(secs(86_400)), Action::Wait(None)); + } + + #[test] + fn key_already_down_at_start_counts_as_a_press() { + let mut button = Button::default(); + button.key(true, secs(0)); + assert_eq!(button.step(secs(0)), Action::Wait(Some(HOLD))); + assert_eq!(button.step(secs(10)), Action::Blink); + } + + #[test] + fn full_hold_blinks_then_wipes_only_on_release() { + let mut button = Button::default(); + button.key(true, secs(5)); + assert_eq!(button.step(secs(14)), Action::Wait(Some(secs(1)))); + assert_eq!(button.step(secs(15)), Action::Blink); + button.blinked(secs(15)); + assert_eq!(button.step(secs(500)), Action::Wait(None)); + button.key(false, secs(500)); + assert_eq!(button.step(secs(500)), Action::Wipe); + } + + #[test] + fn early_release_cancels() { + let mut button = Button::default(); + button.key(true, secs(5)); + button.key(false, secs(14)); + assert_eq!(button.step(secs(14)), Action::Wait(None)); + } + + #[test] + fn queued_early_release_cancels_after_a_delayed_tick() { + let mut button = Button::default(); + button.key(true, secs(5)); + assert_eq!(button.step(secs(20)), Action::Blink); + button.blinked(secs(20)); + button.key(false, secs(14)); + assert_eq!(button.step(secs(20)), Action::Wait(None)); + } + + #[test] + fn complete_hold_released_before_the_cue_also_cancels() { + let mut button = Button::default(); + button.key(true, secs(5)); + assert_eq!(button.step(secs(20)), Action::Blink); + button.blinked(secs(20)); + button.key(false, secs(16)); + assert_eq!(button.step(secs(20)), Action::Wait(None)); + } + + #[test] + fn queued_release_after_the_cue_still_wipes() { + let mut button = Button::default(); + button.key(true, secs(5)); + assert_eq!(button.step(secs(15)), Action::Blink); + button.blinked(secs(15)); + button.key(false, secs(16)); + assert_eq!(button.step(secs(20)), Action::Wipe); + } + + #[test] + fn hold_long_after_boot_still_arms() { + let mut button = Button::default(); + button.key(true, secs(86_400)); + assert_eq!(button.step(secs(86_400)), Action::Wait(Some(HOLD))); + assert_eq!(button.step(secs(86_410)), Action::Blink); + } + + #[test] + fn repeat_events_do_not_restart_the_hold() { + let mut button = Button::default(); + button.key(true, secs(1)); + button.key(true, secs(5)); + assert_eq!(button.step(secs(11)), Action::Blink); + } + + fn event(kind: u16, code: u16, value: i32) -> [u8; EVENT_SIZE] { + let mut bytes = [0u8; EVENT_SIZE]; + bytes[EVENT_TYPE_OFFSET..EVENT_TYPE_OFFSET + 2].copy_from_slice(&kind.to_ne_bytes()); + bytes[EVENT_TYPE_OFFSET + 2..EVENT_TYPE_OFFSET + 4].copy_from_slice(&code.to_ne_bytes()); + bytes[EVENT_TYPE_OFFSET + 4..EVENT_TYPE_OFFSET + 8].copy_from_slice(&value.to_ne_bytes()); + bytes + } + + #[test] + fn parses_only_the_reset_key() { + assert_eq!( + parse_key_event(&event(EV_KEY, KEY_RESTART, 1)).unwrap(), + Some((true, Duration::ZERO)) + ); + assert_eq!( + parse_key_event(&event(EV_KEY, KEY_RESTART, 0)).unwrap(), + Some((false, Duration::ZERO)) + ); + assert_eq!(parse_key_event(&event(EV_SYN, 0, 0)).unwrap(), None); + assert_eq!(parse_key_event(&event(EV_KEY, 116, 1)).unwrap(), None); + } + + #[test] + fn parses_the_kernel_event_timestamp() { + let mut bytes = event(EV_KEY, KEY_RESTART, 0); + bytes[..EVENT_TIME_WORD_SIZE].copy_from_slice(&(12 as libc::c_ulong).to_ne_bytes()); + bytes[EVENT_TIME_WORD_SIZE..EVENT_TIME_WORD_SIZE * 2] + .copy_from_slice(&(345_678 as libc::c_ulong).to_ne_bytes()); + assert_eq!( + parse_key_event(&bytes).unwrap(), + Some((false, Duration::new(12, 345_678_000))) + ); + } + + #[test] + fn lost_input_history_requires_a_watcher_restart() { + assert!(parse_key_event(&event(EV_SYN, SYN_DROPPED, 0)).is_err()); + } +} diff --git a/projects/start-wrt/backend/ctrl/src/lib.rs b/projects/start-wrt/backend/ctrl/src/lib.rs index c041010e56..60a967323a 100644 --- a/projects/start-wrt/backend/ctrl/src/lib.rs +++ b/projects/start-wrt/backend/ctrl/src/lib.rs @@ -21,6 +21,7 @@ pub mod eeprom; pub mod embedded_web; pub mod ethernet; pub mod exec; +pub mod fdl_button; pub mod files; pub mod flash; pub mod http_redirect; diff --git a/projects/start-wrt/backend/ctrl/src/system.rs b/projects/start-wrt/backend/ctrl/src/system.rs index 4bcffa4e0f..8589183203 100644 --- a/projects/start-wrt/backend/ctrl/src/system.rs +++ b/projects/start-wrt/backend/ctrl/src/system.rs @@ -746,13 +746,25 @@ async fn set_preferences( } } -#[instrument(skip_all)] -async fn factory_reset(_ctx: ServerContext) -> Result<(), Error> { - if let Err(e) = tokio::process::Command::new("firstboot") +/// Must not open the activity log: the wipe deletes its directory. +pub(crate) async fn wipe_overlay_and_reboot() -> Result<(), Error> { + run_firstboot().await?; + tokio::process::Command::new("reboot") + .invoke(ErrorKind::Filesystem.into()) + .await?; + Ok(()) +} + +async fn run_firstboot() -> Result<(), Error> { + tokio::process::Command::new("firstboot") .arg("-y") .invoke(ErrorKind::Filesystem.into()) - .await - { + .await?; + Ok(()) +} + +async fn wipe_overlay() -> Result<(), Error> { + if let Err(e) = run_firstboot().await { crate::activity::log( "system", "factory-reset", @@ -760,7 +772,7 @@ async fn factory_reset(_ctx: ServerContext) -> Result<(), Error> { "Failed to initiate factory reset", Some(&e.to_string()), ); - return Err(e.into()); + return Err(e); } crate::activity::log( @@ -771,6 +783,13 @@ async fn factory_reset(_ctx: ServerContext) -> Result<(), Error> { None, ); + Ok(()) +} + +#[instrument(skip_all)] +async fn factory_reset(_ctx: ServerContext) -> Result<(), Error> { + wipe_overlay().await?; + // Spawn reboot after a short delay so the HTTP response can reach the client tokio::spawn(async { tokio::time::sleep(std::time::Duration::from_secs(1)).await; diff --git a/projects/start-wrt/build/stage-files.sh b/projects/start-wrt/build/stage-files.sh index a01d1be3c6..6525e65beb 100755 --- a/projects/start-wrt/build/stage-files.sh +++ b/projects/start-wrt/build/stage-files.sh @@ -68,6 +68,24 @@ start() { DNSINJEOF chmod +x "${FILES_DIR}/etc/init.d/startwrt-dnsinject" +cat > "${FILES_DIR}/etc/init.d/startwrt-fdl-reset" << 'FDLEOF' +#!/bin/sh /etc/rc.common + +START=11 + +USE_PROCD=1 + +start_service() { + procd_open_instance + procd_set_param command /usr/bin/startwrt startwrt-fdl-reset + procd_set_param stdout 1 + procd_set_param stderr 1 + procd_set_param respawn + procd_close_instance +} +FDLEOF +chmod +x "${FILES_DIR}/etc/init.d/startwrt-fdl-reset" + # Custom SmartDNS init script — uses our generated config instead of the # stock UCI-generated one. The stock init script generates its own config # from UCI at /var/etc/smartdns/smartdns.conf, ignoring ours. diff --git a/projects/start-wrt/changelog/minor-added-fdl-factory-reset.md b/projects/start-wrt/changelog/minor-added-fdl-factory-reset.md new file mode 100644 index 0000000000..46088044b4 --- /dev/null +++ b/projects/start-wrt/changelog/minor-added-fdl-factory-reset.md @@ -0,0 +1,5 @@ +--- +release-notes: true +--- + +- On the four-port Start9 Router, holding the factory-reset pinhole button for 10-15 seconds, until the red light blinks rapidly, erases every setting and returns the router to its factory state. diff --git a/projects/start-wrt/docs/src/factory-reset.md b/projects/start-wrt/docs/src/factory-reset.md index 185f3ac850..0733719cb5 100644 --- a/projects/start-wrt/docs/src/factory-reset.md +++ b/projects/start-wrt/docs/src/factory-reset.md @@ -1,6 +1,6 @@ # Factory Reset -A factory reset restores StartWRT to its default state at unboxing. There are two ways to reset: from the web interface (soft reset) or from a microSD card (reflash). +A factory reset restores StartWRT to its default state at unboxing. You can reset from the web interface or the factory-reset button (soft reset), or from a microSD card (reflash). ## Soft Reset (Web Interface) @@ -21,6 +21,23 @@ The router will reboot. After reboot: > [!WARNING] > A factory reset cannot be undone. Create a [backup](backups.md) first if you want to preserve your settings. +## Soft Reset (Factory-Reset Button) + +The four-port Start9 Router has two pinhole buttons. The one next to the power jack is the factory-reset button. The one next to the USB-A port is the reset button, which only restarts the router. The single LAN port Start9 Router has no buttons. + +The factory-reset button is a last resort for when you cannot reach the web interface. It performs the same soft reset as the web interface: every setting is erased and the router returns to its factory state. It works at any time while the router is on. + +> [!WARNING] +> Use the factory-reset button only when nothing else works. It wipes the entire router configuration and cannot be undone. If you can still log in, create a [backup](backups.md) first. + +1. With the router on, press and hold the factory-reset button with a paperclip or similar. The red light keeps pulsing slowly at first. + +1. Keep holding for 10-15 seconds, until the red light changes to a rapid blink. + +1. Release the button. The router erases its settings and reboots. It comes back in the state described above, with the red light pulsing slowly again. + +Letting go before the red light blinks rapidly cancels the reset. + ## Reflash (microSD) A microSD reflash boots the router from a StartWRT image and replaces the firmware entirely. The router enters setup mode and brings up the `StartWRT` Wi-Fi network limited to a single client, with a captive portal that auto-opens the setup wizard. diff --git a/projects/start-wrt/docs/src/faq.md b/projects/start-wrt/docs/src/faq.md index fb414b889a..6ef272a3bb 100644 --- a/projects/start-wrt/docs/src/faq.md +++ b/projects/start-wrt/docs/src/faq.md @@ -34,7 +34,7 @@ Yes. StartWRT is built on OpenWrt, and the full CLI is accessible over [SSH](ssh You have two options: -1. **Factory reset** — Perform a [factory reset](factory-reset.md) from the web interface (if you are still logged in). This wipes all settings; Wi-Fi comes back up with the sticker password. +1. **Factory reset** — Perform a [factory reset](factory-reset.md) from the web interface (if you are still logged in) or, on the four-port Start9 Router, with the factory-reset button. This wipes all settings; Wi-Fi comes back up with the sticker password. 2. **Reflash** — Boot from a microSD card and choose "Keep settings" to reinstall the firmware while preserving settings. You will be prompted to create a new admin password. See [Installing StartWRT](installing.md). ## What if I lose my Wi-Fi sticker password? diff --git a/projects/start-wrt/openwrt-overlay/target/linux/spacemit/dts/k1-x_deb1.dts b/projects/start-wrt/openwrt-overlay/target/linux/spacemit/dts/k1-x_deb1.dts new file mode 100644 index 0000000000..7491884dcd --- /dev/null +++ b/projects/start-wrt/openwrt-overlay/target/linux/spacemit/dts/k1-x_deb1.dts @@ -0,0 +1,28 @@ +#include "spacemit/k1-x_deb1.dts" +#include + +/ { + gpio-keys { + compatible = "gpio-keys"; + pinctrl-names = "default"; + pinctrl-0 = <&pinctrl_fdl>; + + fdl { + label = "FDL"; + gpios = <&gpio 98 0>; + linux,code = ; + }; + }; +}; + +&pinctrl { + pinctrl_fdl: fdl_grp { + pinctrl-single,pins = < + K1X_PADCONF(QSPI_DAT3, MUX_MODE1, (EDGE_NONE | PULL_DOWN | PAD_3V_DS4)) + >; + }; +}; + +&qspi { + status = "disabled"; +}; diff --git a/projects/start-wrt/openwrt-overlay/target/linux/spacemit/image/k1-sbc.mk b/projects/start-wrt/openwrt-overlay/target/linux/spacemit/image/k1-sbc.mk index be3be67a12..c442bca87f 100644 --- a/projects/start-wrt/openwrt-overlay/target/linux/spacemit/image/k1-sbc.mk +++ b/projects/start-wrt/openwrt-overlay/target/linux/spacemit/image/k1-sbc.mk @@ -5,7 +5,7 @@ define Device/bananapi-f3 DEVICE_VENDOR := Banana Pi DEVICE_MODEL := BPI-F3 - DEVICE_DTS_DIR := $(DTS_DIR)/spacemit + DEVICE_DTS_DIR := ../dts DEVICE_DTS := k1-x_deb1 # The k1-x_deb1.dts root only exposes the SoC-level compatible # "spacemit,k1-x", so board_detect populates /tmp/sysinfo/board_name with From f8d83990b4e3cc14261e711e8ef76638622c70f5 Mon Sep 17 00:00:00 2001 From: Dominion5254 Date: Thu, 19 Nov 2026 16:06:27 -0700 Subject: [PATCH 22/38] fix(start-wrt): resolve a moved device at its new address from the profile it left (#4692) A device that moves to another Security Profile keeps its lease on the profile it left until that lease expires, up to 12 hours. The refresher counted every lease a profile's own instance held as that profile's claim on the name, so it left the name out of that profile's hosts file and the instance kept answering the old lease's address: after moving a machine off Admin, `ssh ` from Admin went to an address nobody held until the old lease ran out. A profile now claims a name only from each device's newest lease, the same lease the device's address is taken from. A moved device's name is written into the old profile's hosts file at its new address, and dnsmasq prefers the hosts file over the old lease's `.lan`. A raw query for the bare name still returns the old lease until it expires; clients that append the `lan` search domain ask for `.lan` first. Two different devices sharing a name are unchanged: the profile's own device keeps it. --- .../start-wrt/backend/ctrl/src/dns_inject.rs | 68 +++++++++++++++---- .../patch-fixed-moved-device-name.md | 5 ++ 2 files changed, 59 insertions(+), 14 deletions(-) create mode 100644 projects/start-wrt/changelog/patch-fixed-moved-device-name.md diff --git a/projects/start-wrt/backend/ctrl/src/dns_inject.rs b/projects/start-wrt/backend/ctrl/src/dns_inject.rs index e8418473f5..dd0ec3009e 100644 --- a/projects/start-wrt/backend/ctrl/src/dns_inject.rs +++ b/projects/start-wrt/backend/ctrl/src/dns_inject.rs @@ -181,9 +181,9 @@ struct HostName { #[derive(Clone, Debug, Default, PartialEq, Eq)] struct HostNames { entries: Vec, - /// Profile → lowercase names its own leases carry. That profile's - /// instance serves them itself and refuses a lease a name it already has - /// at another address. + /// Profile → lowercase names its own leases carry, counting only each + /// device's newest lease. That profile's instance serves them itself and + /// refuses a lease a name it already has at another address. leased: BTreeMap>, } @@ -474,22 +474,25 @@ fn host_names(snapshot: &NetSnapshot, leases: &[crate::devices::DhcpLease]) -> H let Ok(ip) = lease.ip.parse::() else { continue; }; - if let Some(p) = profile_for(&snapshot.profiles, ip) { - if lease.instance.as_deref() == Some(format!("dns_{}", p.interface).as_str()) - && valid(&lease.hostname) - { - hosts - .leased - .entry(p.interface.clone()) - .or_default() - .insert(lease.hostname.to_ascii_lowercase()); - } - } let held = newest.entry(lease.mac.as_str()).or_insert((lease, ip)); if expiry(lease) > expiry(held.0) { *held = (lease, ip); } } + for (lease, ip) in newest.values() { + let Some(p) = profile_for(&snapshot.profiles, *ip) else { + continue; + }; + if lease.instance.as_deref() == Some(format!("dns_{}", p.interface).as_str()) + && valid(&lease.hostname) + { + hosts + .leased + .entry(p.interface.clone()) + .or_default() + .insert(lease.hostname.to_ascii_lowercase()); + } + } let macs: BTreeSet<&str> = newest .keys() .copied() @@ -2556,6 +2559,43 @@ mod tests { ); } + #[test] + fn a_moved_device_resolves_at_its_new_lease_from_its_old_profile() { + let (snapshot, _) = name_fixture(); + let reach = BTreeSet::from([ + ("lan".into(), "vlan_guest".into()), + ("vlan_guest".into(), "lan".into()), + ]); + let moved = |lan_expires, guest_expires| { + [ + lease( + "dns_lan", + "EE:00:00:00:00:01", + Ipv4Addr::new(192, 168, 1, 110), + "debian", + lan_expires, + ), + lease( + "dns_guest", + "EE:00:00:00:00:01", + Ipv4Addr::new(192, 168, 101, 110), + "debian", + guest_expires, + ), + ] + }; + assert_eq!( + rendered_names(&snapshot, &reach, &moved(1_000_000_000, 2_000_000_000))[..2], + ["192.168.101.110 debian.lan\n".to_string(), String::new()], + "lan's older lease of the device yields the name to its guest lease" + ); + assert_eq!( + rendered_names(&snapshot, &reach, &moved(2_000_000_000, 1_000_000_000))[..2], + [String::new(), "192.168.1.110 debian.lan\n".to_string()], + "moved back: lan's lease is the newest again and serves the name itself" + ); + } + /// The rendered files encode the directory, so a refresh wakes the /// renderer even when no record changed. #[tokio::test] diff --git a/projects/start-wrt/changelog/patch-fixed-moved-device-name.md b/projects/start-wrt/changelog/patch-fixed-moved-device-name.md new file mode 100644 index 0000000000..4466839900 --- /dev/null +++ b/projects/start-wrt/changelog/patch-fixed-moved-device-name.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- After a device moves to another Security Profile, its name resolves to its new address from the network it left within a minute, instead of to its old address for up to 12 hours. From 27efae76f39b905eeac8cfecdf2571485d40d748 Mon Sep 17 00:00:00 2001 From: Dominion5254 Date: Thu, 19 Nov 2026 16:09:17 -0700 Subject: [PATCH 23/38] fix(start-wrt): hide the PPPoE password from the WAN IPv4 summary (#4780) * fix(start-wrt): hide the PPPoE password from the WAN IPv4 summary The WAN IPv4 summary listed every PPPoE field, so the stored password rendered in clear text with a copy button above the masked form input. Drop it from the summary fields; the form input keeps it editable. * Proposed changes for #4780 Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol --------- Co-authored-by: helix-white <267227783+helix-a@users.noreply.github.com> --- .../changelog/patch-security-wan-summary-password.md | 5 +++++ .../start-wrt/web/src/app/routes/wan/routes/ipv4/summary.ts | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) create mode 100644 projects/start-wrt/changelog/patch-security-wan-summary-password.md diff --git a/projects/start-wrt/changelog/patch-security-wan-summary-password.md b/projects/start-wrt/changelog/patch-security-wan-summary-password.md new file mode 100644 index 0000000000..3bad36b622 --- /dev/null +++ b/projects/start-wrt/changelog/patch-security-wan-summary-password.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Stop showing the PPPoE password in the WAN IPv4 summary. diff --git a/projects/start-wrt/web/src/app/routes/wan/routes/ipv4/summary.ts b/projects/start-wrt/web/src/app/routes/wan/routes/ipv4/summary.ts index a984c16a21..f3bca19739 100644 --- a/projects/start-wrt/web/src/app/routes/wan/routes/ipv4/summary.ts +++ b/projects/start-wrt/web/src/app/routes/wan/routes/ipv4/summary.ts @@ -6,13 +6,13 @@ import { WanIpv4Form, IPV4_LABELS, netmaskFromPrefix } from './utils' import { WanIpv4Service } from './service' import { i18nPipe } from 'src/app/i18n/i18n.pipe' +// Summary rows must exclude the PPPoE password. const SUMMARY_FIELDS = [ 'wan', 'prefix', 'mask', 'gateway', 'username', - 'password', 'device', ] as const From 5805c539d80c37fa76641459927dd702d8853981 Mon Sep 17 00:00:00 2001 From: gStart9 <106188942+gStart9@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:10:59 +0000 Subject: [PATCH 24/38] docs(start-cli): show how to pass a key to ssh add (#4759) * docs(start-cli): show how to pass a key to ssh add The help for `start-cli ssh add` said only "SSH public key", which left users passing a file path or an unquoted key line. The help now shows the key line passed as one quoted argument. Co-Authored-By: Claude Opus 5.5 * docs(start-cli): regenerate the ssh add man page Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- projects/start-cli/man/start-cli-ssh-add.1 | 2 +- shared-libs/crates/start-core/locales/i18n.yaml | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/projects/start-cli/man/start-cli-ssh-add.1 b/projects/start-cli/man/start-cli-ssh-add.1 index 196b2f8cfd..3144b96f07 100644 --- a/projects/start-cli/man/start-cli-ssh-add.1 +++ b/projects/start-cli/man/start-cli-ssh-add.1 @@ -13,4 +13,4 @@ Add ssh key Print help .TP <\fIKEY\fR> -SSH public key +SSH public key, passed as one quoted argument, e.g. "$(cat ~/.ssh/id_ed25519.pub)" diff --git a/shared-libs/crates/start-core/locales/i18n.yaml b/shared-libs/crates/start-core/locales/i18n.yaml index 7d83c794ed..ace8e2fc58 100644 --- a/shared-libs/crates/start-core/locales/i18n.yaml +++ b/shared-libs/crates/start-core/locales/i18n.yaml @@ -6025,11 +6025,11 @@ help.arg.ssh-fingerprint: pl_PL: "Odcisk palca klucza SSH" help.arg.ssh-public-key: - en_US: "SSH public key" - de_DE: "Öffentlicher SSH-Schlüssel" - es_ES: "Clave pública SSH" - fr_FR: "Clé publique SSH" - pl_PL: "Klucz publiczny SSH" + en_US: "SSH public key, passed as one quoted argument, e.g. \"$(cat ~/.ssh/id_ed25519.pub)\"" + de_DE: "Öffentlicher SSH-Schlüssel, als ein Argument in Anführungszeichen übergeben, z. B. \"$(cat ~/.ssh/id_ed25519.pub)\"" + es_ES: "Clave pública SSH, pasada como un único argumento entre comillas, p. ej. \"$(cat ~/.ssh/id_ed25519.pub)\"" + fr_FR: "Clé publique SSH, passée comme un seul argument entre guillemets, p. ex. \"$(cat ~/.ssh/id_ed25519.pub)\"" + pl_PL: "Klucz publiczny SSH, przekazany jako jeden argument w cudzysłowie, np. \"$(cat ~/.ssh/id_ed25519.pub)\"" help.arg.tunnel-ip-address: en_US: "Tunnel server IP address" From 20aada4aa3c5bce6095cbc52d0eb871cb730628f Mon Sep 17 00:00:00 2001 From: "start9-docs-bot[bot]" <315476469+start9-docs-bot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:16:42 +0000 Subject: [PATCH 25/38] docs: backport live-docs 20466b24c to master Backports the following from live-docs: - 20466b24c docs(start-os): show how to pass a key to ssh add, and fix ssh remove's argument (#4760) --- projects/start-os/docs/src/cli-reference.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/projects/start-os/docs/src/cli-reference.md b/projects/start-os/docs/src/cli-reference.md index 2ee3b01696..52da1b1138 100644 --- a/projects/start-os/docs/src/cli-reference.md +++ b/projects/start-os/docs/src/cli-reference.md @@ -675,7 +675,11 @@ Manage authorized SSH keys for server access. ### `start-cli ssh add ` -Add an SSH public key. +Add an SSH public key. Pass the key's text, not its path, as a single quoted argument: + +```sh +start-cli ssh add "$(cat ~/.ssh/id_ed25519.pub)" +``` ### `start-cli ssh list` @@ -683,9 +687,9 @@ List authorized SSH keys. - `--format` — Output format -### `start-cli ssh remove ` +### `start-cli ssh remove ` -Remove an SSH key. +Remove an SSH key by the fingerprint `start-cli ssh list` shows for it. ## WiFi From 88bb0d2337c2990c0642836a4567c5352de10263 Mon Sep 17 00:00:00 2001 From: "start9-docs-bot[bot]" <315476469+start9-docs-bot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:27:18 +0000 Subject: [PATCH 26/38] docs: backport live-docs 8fe841760 to master Backports the following from live-docs: - 8fe841760 docs: describe the Let's Encrypt port 443 test as advisory (#4639) --- projects/start-os/docs/src/clearnet.md | 19 ++++++++++++++++--- projects/start-os/docs/src/faq.md | 2 +- .../start-tunnel/docs/src/published-ports.md | 4 +++- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/projects/start-os/docs/src/clearnet.md b/projects/start-os/docs/src/clearnet.md index 4b3f9b3656..f11a24cefa 100644 --- a/projects/start-os/docs/src/clearnet.md +++ b/projects/start-os/docs/src/clearnet.md @@ -29,7 +29,7 @@ If your gateway is your home router, you are revealing the approximate location | **IP stability** | Home IP can change without warning, breaking all your domains until DNS is updated. [Dynamic DNS](https://en.wikipedia.org/wiki/Dynamic_DNS) is highly recommended, but support varies by router and may cost money. | Static IP from the VPS provider. No dynamic DNS needed. | | **Privacy** | Exposes your home's approximate location | Exposes the VPS location, not your home | | **CGNAT compatible** | No. If your ISP uses [CGNAT](cgnat.md), you cannot use your router as a gateway. | Yes | -| **Port forwarding** | Configured in router admin panel | Configured in [StartTunnel](/start-tunnel/port-forwarding.html) | +| **Port forwarding** | Configured in router admin panel | Configured in [StartTunnel](/start-tunnel/published-ports.html) | ## Add a Public Domain @@ -46,7 +46,7 @@ If your gateway is your home router, you are revealing the approximate location 1. StartOS automatically tests your DNS record and port forwarding — plus the IPv6 firewall when your gateway has a GUA, and port `443` for a Let's Encrypt domain served on any other port. If everything passes, the domain is ready to use. Otherwise a setup modal appears showing what still needs attention, with instructions and the ability to re-test each check. > [!NOTE] - > The port `443` test is what tells you a Let's Encrypt domain will work: the authority validates there regardless of which port the address itself uses, and until the first certificate is issued the address answers nothing. The test applies while the domain is waiting on that certificate and again through each renewal window — a domain being renewed keeps serving the certificate it holds, so keep `443` forwarded and it renews without interruption. See [Configure Port Forwarding](#configure-port-forwarding); the rule also appears under **System → Gateways → Port Forwards**. + > The port `443` test is advisory: StartOS requests a Let's Encrypt certificate the first time a TLS connection for the domain reaches its service port, whether or not the test passed. The authority validates on port `443` regardless of which port the address itself uses, and until the first certificate is issued the address answers nothing. The test applies while the domain is waiting on that certificate and again through each renewal window — a domain being renewed keeps serving the certificate it holds, so keep `443` forwarded and it renews without interruption. See [Configure Port Forwarding](#configure-port-forwarding); the rule also appears under **System → Gateways → Port Forwards**. ## Set Up DNS Records @@ -60,6 +60,9 @@ StartOS tests DNS automatically when you add or enable a public domain, and will If you use subdomains, consider using a wildcard (`*`) for that host so that all future subdomains work without needing additional records. + > [!WARNING] + > If your DNS is on Cloudflare, set the record to **DNS only**. A proxied record (the orange cloud) points the name at Cloudflare instead of your gateway, so the DNS test fails and Let's Encrypt cannot validate the domain. + > [!TIP] > It can take up to a few hours for DNS changes to propagate. You can check propagation using [https://dnschecker.org](https://dnschecker.org). @@ -77,9 +80,19 @@ When a public address is enabled, StartOS first **attempts to open the port auto > [!IMPORTANT] > A Let's Encrypt domain needs port `443` even when its interface is served somewhere else — an Electrum server on `50002`, for example. Let's Encrypt proves you control a name by connecting to it on port `443`, regardless of which port the service behind it uses, and StartOS answers there for every domain it holds an authority for. Over StartTunnel, StartOS claims `443` for that domain automatically alongside the interface's own port, and over IPv6 it opens the matching `443` pinhole, so there is nothing to do. On a router, forward `443` to your server as you would for a standard domain, and keep it forwarded — the certificate is renewed the same way, and the rule is listed for you under **System → Gateways → Port Forwards**. Such a domain is served on its own port only, so reach it as `https://:`. Choose **Local Root CA** instead for a domain whose gateway cannot offer port `443`. +> +> To confirm the StartTunnel route, open **Published Ports** in StartTunnel: the **Automatic** table should list port `443` to your server with the exact domain as its hostname. If it is missing, check that auto-publish is on for the server, or add the entry by hand — External `443`, your server, Internal `443`, IPv4, and the domain as its [Hostname](/start-tunnel/published-ports.html#sni-hostnames-ipv4-only). How you create a port forwarding rule depends on the type of gateway. - **Routers**: Port forwarding is supported by all routers and easy to do. Many routers also support PCP, NAT-PMP, or UPnP, in which case StartOS opens the port for you automatically. If none is available or they are disabled, refer to your router's manual to add the rule manually. -- **StartTunnel**: StartTunnel supports PCP and UPnP over the tunnel, so StartOS opens the required port automatically. To add or manage forwards manually, refer to the [StartTunnel Port Forwarding guide](/start-tunnel/port-forwarding.html). +- **StartTunnel**: StartTunnel supports PCP and UPnP over the tunnel, so StartOS opens the required port automatically. To add or manage forwards manually, refer to the [StartTunnel Published Ports guide](/start-tunnel/published-ports.html). + +## Troubleshooting Let's Encrypt + +- **`Network Error … error sending request for url (https://ifconfig.co/port/443)`.** StartOS could not reach the outside services it asks to test the port (`ipconfig.io` and `ifconfig.co` by default). That says nothing about whether the port is open, and it does not block the certificate. Over StartTunnel, StartOS skips them when an automatic mapping for the port reports a public IP, so this error means either no automatic mapping is active or, on a StartTunnel host behind upstream NAT, it reports a private IP: check **Published Ports** as described in [Configure Port Forwarding](#configure-port-forwarding). To test the port yourself, run `curl -v https://ifconfig.co/port/443` on the VPS, not on your server, which would test your home connection instead. + +- **No certificate, no "Could not get a certificate" notification, and no ACME lines in the logs** (such as `performing ACME auth challenge` or `ACME order failed`). Connect to the domain on the service's actual port to trigger issuance — for example, `50002` for an Electrum interface. Port `443` carries validation, but a normal connection to `443` does not trigger an order for a domain served only on another port. If there are still no ACME messages, check the Let's Encrypt configuration, the DNS record, and forwarding for both the service port and `443`. + +- **A "Could not get a certificate for …" notification.** The order failed or timed out. The notification gives the reason. diff --git a/projects/start-os/docs/src/faq.md b/projects/start-os/docs/src/faq.md index 901cd45dc1..e1e4031571 100644 --- a/projects/start-os/docs/src/faq.md +++ b/projects/start-os/docs/src/faq.md @@ -108,7 +108,7 @@ If you would rather not use a terminal, paste the domain into [dnschecker.org](h - **The domain is private.** A private domain has no public record, so a public resolver never answers for it. It resolves only through the DNS server of the gateway it was added to: on an Ethernet or WiFi gateway your router must hand out StartOS as its DNS server, and on a StartTunnel gateway your device must be connected to the tunnel _and_ using the tunnel's resolver, with [DNS injection](/start-tunnel/dns-records.html) enabled for the server (the default). A phone runs only one VPN at a time, so turning on a privacy VPN such as ProtonVPN or Mullvad disconnects your StartTunnel tunnel and takes its resolver with it; private domains stop resolving until you switch back. If your device is connected and still gets no answer, check that the record appears on StartTunnel's DNS Records page, then re-import a freshly generated config for the device: configs generated before StartTunnel 1.1.0 have no `DNS =` line, so the device keeps asking its usual resolver. If the private domain is also a real domain with public records, a device that is not using the gateway's resolver gets the public answer instead, which can look like the name works while it points somewhere else entirely. -- **The answer is the right address, but the page still does not load.** The right address is your gateway's public IP for a public domain, and your server's LAN IP or tunnel address for a private one. DNS is not the problem. For a private domain, confirm the device is actually on that network (the tunnel is connected, or you are on the LAN) and that you have [trusted your Root CA](trust-ca.md). For a public domain, run the port-forwarding test from the address's **Settings** on the service's [Interfaces](interfaces.md) tab. +- **The answer is the right address, but the page still does not load.** The right address is your gateway's public IP for a public domain, and your server's LAN IP or tunnel address for a private one. DNS is not the problem. For a private domain, confirm the device is actually on that network (the tunnel is connected, or you are on the LAN) and that you have [trusted your Root CA](trust-ca.md). For a public domain, run the port-forwarding test from the address's **Settings** on the service's [Interfaces](interfaces.md) tab. If the domain uses Let's Encrypt and has no certificate yet, see [Troubleshooting Let's Encrypt](clearnet.md#troubleshooting-lets-encrypt). ## A public domain still loads after disabling it diff --git a/projects/start-tunnel/docs/src/published-ports.md b/projects/start-tunnel/docs/src/published-ports.md index 1a579d990e..684d562f5e 100644 --- a/projects/start-tunnel/docs/src/published-ports.md +++ b/projects/start-tunnel/docs/src/published-ports.md @@ -51,4 +51,6 @@ SNI hostnames can share the enabled admin UI's listen port. Connections with an A device can access its own service through its published SNI hostname or the shared port's fallback. For these hairpin connections, the service sees StartTunnel's in-tunnel address as the client. Connections from other devices retain their original client address. -Connected devices can also create SNI hostname routes **automatically**, the same way they open automatic ports. A device asks over PCP (preferred) or, when PCP can't get through, over a UPnP vendor action the tunnel advertises (`X_START9_AddHostnameMapping`). Either way the route appears in the **Automatic** table, carries a lease, and expires on its own if the device stops renewing it — and, like every automatic mapping, it can only point at the requesting device's own address. +The admin UI listens on `8443` by default. If you move it to `443`, a domain with no hostname route there reaches the admin UI instead of your server, so Let's Encrypt cannot validate it, even though a port test still finds something answering. + +Connected devices can also create SNI hostname routes **automatically**, the same way they open automatic ports. A device asks over PCP (preferred) or, when PCP can't get through, over a UPnP vendor action the tunnel advertises (`X_START9_AddHostnameMapping`). Either way the route appears in the **Automatic** table, carries a lease, and expires on its own if the device stops renewing it — and, like every automatic mapping, it can only point at the requesting device's own address. A StartOS server requests a `443` hostname route this way for each of its Let's Encrypt domains, so the domain appears in the **Automatic** table with `443` as its port; see [Configure Port Forwarding](/start-os/clearnet.html#configure-port-forwarding). From c01550f98bdfb4c7eafd0dbf320745e067a0e58f Mon Sep 17 00:00:00 2001 From: "start9-docs-bot[bot]" <315476469+start9-docs-bot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:32:11 +0000 Subject: [PATCH 27/38] docs: backport live-docs 24c9a8e0c to master Backports the following from live-docs: - 24c9a8e0c docs(start-wrt): explain outages from a profile on the WAN subnet (#4744) --- projects/start-wrt/docs/src/faq.md | 12 ++++++++++++ projects/start-wrt/docs/src/initial-setup.md | 2 ++ projects/start-wrt/docs/src/security-profiles.md | 2 +- 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/projects/start-wrt/docs/src/faq.md b/projects/start-wrt/docs/src/faq.md index 6ef272a3bb..a816eeff3a 100644 --- a/projects/start-wrt/docs/src/faq.md +++ b/projects/start-wrt/docs/src/faq.md @@ -160,6 +160,18 @@ If the network you are visiting uses the same addresses as your home network, yo StartWRT's default addresses (`192.168.0.x` for the Admin profile, then `192.168.1.x` for the next profile) are among the most common on home, hotel, and office networks. To avoid the overlap, choose a less common **Network Block** in [LAN Settings](lan.md#ipv4), such as `10.47`. Changing the Network Block removes your existing [Inbound VPN](inbound-vpn.md) servers, so do it before setting up remote access, or recreate the servers and re-import their client configurations afterward. +### Why does the Internet stop every few minutes while Wi-Fi stays connected? + +If StartWRT sits behind another router (for example an ISP router or gateway), check that none of your [Security Profiles](security-profiles.md) overlaps that router's LAN subnet. Many ISP routers use `192.168.1.1` or `192.168.0.1`, and StartWRT's Admin profile defaults to `192.168.0.x`, with the next profile you add defaulting to `192.168.1.x`. An overlap can interrupt IPv4 Internet access for a minute or two at a time while Wi-Fi stays connected, and make devices on the upstream LAN unreachable. If a profile's gateway is also the upstream router's address, StartWRT may ignore that router's DNS servers. + +To check, look at **Assigned IP** under **IPv4** in [WAN Settings](wan.md), and check the upstream router's LAN subnet mask in its own settings. For an upstream `/24` (`255.255.255.0`), the first three numbers must match a profile's full subnet: `192.168.1.221` overlaps `192.168.1.0/24`, not `10.47.1.0/24`. The first two numbers of a profile's subnet come from StartWRT's **Network Block** in [LAN Settings](lan.md#ipv4), and the third is the profile's **Subnet**. If the upstream mask is not `/24`, compare the full address ranges instead. If any profile overlaps, do one of the following: + +- Change that profile's **Subnet** to an unused number outside the upstream LAN range, such as `10` when the upstream LAN is `192.168.1.0/24`. See [Editing a Profile](security-profiles.md#editing-a-profile). If that profile is **Admin**, which overlaps an upstream router at `192.168.0.1` by default, this also changes the router's own address, for example to `192.168.10.1`. Reconnect your device if needed, then open the web interface at the new address or at `router.lan`. +- Change StartWRT's **Network Block** in [LAN Settings](lan.md#ipv4) to a range outside the upstream LAN, such as `10.47` behind a `192.168.x.x` network. This moves every profile, including the router's own address. +- Change the other router's LAN address to a range StartWRT does not use. + +Changing a profile's subnet or the Network Block is blocked while affected devices have static IP reservations, so remove those first. If affected profiles have [Inbound VPN](inbound-vpn.md) clients, saving asks for confirmation to delete their VPN servers. Recreate those servers and import new client configurations afterward. + ### Why doesn't the router get an Internet address after I replaced my old router? Some ISPs only give an address to the device they already know, which they identify by its MAC address. In [WAN Settings](wan.md#mac-address), set **MAC Address** to **Custom** and enter the MAC address of your old router's Internet port. Take it from the old router's admin page, not its label, which usually shows a different port's address. Then disconnect the old router. diff --git a/projects/start-wrt/docs/src/initial-setup.md b/projects/start-wrt/docs/src/initial-setup.md index 683e6e51ae..c20e1d80e5 100644 --- a/projects/start-wrt/docs/src/initial-setup.md +++ b/projects/start-wrt/docs/src/initial-setup.md @@ -6,6 +6,8 @@ After unboxing your Start9 router or completing a fresh install, follow these st 1. Connect your modem or upstream router to the Ethernet port labeled **WAN**, and the included switch to the port labeled **LAN**, for wired devices on your network. + If you connect StartWRT behind another router rather than a modem, note that router's LAN address and subnet mask (often `192.168.0.1/24` or `192.168.1.1/24`). StartWRT's networks must not overlap that LAN range. See the [FAQ](faq.md#why-does-the-internet-stop-every-few-minutes-while-wi-fi-stays-connected). + 1. Power on the router. 1. Connect your phone or computer to the router, either: diff --git a/projects/start-wrt/docs/src/security-profiles.md b/projects/start-wrt/docs/src/security-profiles.md index 7e885789f0..b029c3f80f 100644 --- a/projects/start-wrt/docs/src/security-profiles.md +++ b/projects/start-wrt/docs/src/security-profiles.md @@ -32,7 +32,7 @@ One SSID, multiple passwords. One router, multiple isolated networks. The profil 1. Enter a **Name** at the top of the dialog (e.g. "Admin", "Guest", "Children", "Smart Devices"). The Name field sits above three tabs — **LAN**, **WAN / Internet**, and **DNS**. 1. On the **LAN** tab, configure local-network settings: - - **Subnet** — Set the third octet of the profile's `/24` subnet. The first two octets are shown but locked; for example, a value of `2` creates the subnet `192.168.2.0/24`. They are locked because every profile must stay within the primary [LAN network block](lan.md)'s `/16` for cross-subnet routing to work — changing the LAN network block moves all profiles with it. Each profile must have a unique subnet. The gateway address is always `.1` within the subnet (e.g. `192.168.2.1`). + - **Subnet** — Set the third octet of the profile's `/24` subnet. The first two octets are shown but locked; for example, a value of `2` creates the subnet `192.168.2.0/24`. They are locked because every profile must stay within the primary [LAN network block](lan.md)'s `/16` for cross-subnet routing to work — changing the LAN network block moves all profiles with it. Each profile must have a unique subnet. The gateway address is always `.1` within the subnet (e.g. `192.168.2.1`). Don't choose a subnet that overlaps your ISP router's LAN subnet or another upstream network. An overlap can interrupt Internet access. See the [FAQ](faq.md#why-does-the-internet-stop-every-few-minutes-while-wi-fi-stays-connected). - **Access** — Controls which other profiles this profile can communicate with on the local network: - **All** — Full access to devices on all profiles. From 7b31373c8e0559d32d634df5b86af9700113f514 Mon Sep 17 00:00:00 2001 From: "start9-docs-bot[bot]" <315476469+start9-docs-bot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:34:02 +0000 Subject: [PATCH 28/38] docs: backport live-docs 201de9412 to master Backports the following from live-docs: - 201de9412 docs(start-sdk): registry setup uses Manage Registries and Manage Signers (#4719) --- .../start-sdk/docs/src/host-registry-setup.md | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/projects/start-sdk/docs/src/host-registry-setup.md b/projects/start-sdk/docs/src/host-registry-setup.md index 4780a774ff..d7ca803610 100644 --- a/projects/start-sdk/docs/src/host-registry-setup.md +++ b/projects/start-sdk/docs/src/host-registry-setup.md @@ -1,20 +1,22 @@ # Setup -The packaged `startos-registry` service is the supported way to run a registry. Install it from any registry that carries it (the Start9 registry does), complete two first-run actions, and you're ready to publish. +The packaged `startos-registry` service is the supported way to run a registry. Install it from any registry that carries it (the Start9 registry does), name the registry and register an administrator, and you're ready to publish. ## 1. Install the service From StartOS, open the Marketplace, find **StartOS Registry**, and install. The service has no external dependencies. Once installed, start it. -On first install, StartOS surfaces two setup tasks under the service. **Both must be completed before the registry is usable.** +A fresh install starts one registry, and StartOS surfaces two setup tasks under the service: **Manage Registries** and **Manage Signers**. They don't block the service from starting, but nobody can publish to the registry until Manage Signers has registered an administrator. -## 2. Configure Registry +## 2. Name and describe the registry -Run the **Configure Registry** action to set the registry's display name (max 32 characters), an optional icon, and an optional description. This is what users will see when they browse your registry from another StartOS device; the description appears above the registry's services and may use markdown. +Run the **Manage Registries** action to name the registry (1–32 characters). This is what users see when they browse your registry from another StartOS device. The same action can add more registries to the service, each with its own catalog, signers, and addresses. + +Then run **Configure Registry**, choose the registry by name, and set an optional icon and description for it. The description appears above the registry's services and may use markdown. Use the description to identify who runs the registry, how to contact them, what packages it carries, and what support users can expect. Include a link to your package-signing public keys and instructions for verifying them. -The registry's hostnames, listen address, Tor proxy, and data directory are managed by StartOS automatically — you don't configure them by hand. As the service's network addresses change (e.g. you add a clearnet domain to the API interface), the configured hostnames update to match. +The registry's hostnames, listen address, Tor proxy, and data directory are managed by StartOS automatically — you don't configure them by hand. As the service's network addresses change (e.g. you add a clearnet domain to the registry's **Web API — _registry name_** interface), the configured hostnames update to match. ### Publish signing keys @@ -42,7 +44,9 @@ it added. Manage package trust under System → Trusted Keys; see ## 3. Add the first administrator -Run **Add Administrator** to register the first admin. You'll need a PEM-encoded Ed25519 public key, a label, and contact info (email or Matrix handle). Admins can manage signers, publish packages, register OS versions, and edit categories. +Run **Manage Signers**, expand the section bearing the registry's name, and add an entry to its **Signers** list. Give it a label and paste your public key into **Public Keys**: a PEM-encoded Ed25519 public key, or a complete armored GPG export of an Ed25519 key. Contacts (email addresses, Matrix usernames, or URLs) are optional. Turn on **Admin**. Admins can manage signers, publish packages, register OS versions, and edit categories. + +**Offer for Trust**, on the same entry, is separate from **Admin**: it offers the signer's keys to users who connect the registry. See [Offering signing keys to users](host-registry-administration.md#offering-signing-keys-to-users) before turning it on. To generate a key on your workstation: @@ -51,7 +55,7 @@ start-cli init-key start-cli pubkey ``` -`init-key` creates an Ed25519 keypair at `~/.startos/id.key.pem` (or `/run/startos/id.key.pem` if running on a StartOS device). `pubkey` prints the public half — that's what you paste into the **Public Key** field of the Add Administrator action. +`init-key` creates an Ed25519 keypair at `~/.startos/id.key.pem` (or `/run/startos/id.key.pem` if running on a StartOS device). `pubkey` prints the public half — that's what you paste into the **Public Keys** field in Manage Signers. Treat the private key like an SSH key: it authenticates every admin and publish action you take against the registry. Back it up. @@ -59,20 +63,20 @@ To keep the key in gpg-agent instead, skip `init-key` and point `start-cli` at a ## 4. Point `start-cli` at the registry -All registry operations go through `start-cli registry` (or `start-cli s9pk publish` for uploading packages). Pass the registry's URL with `--registry`: +All registry operations go through `start-cli registry` (or `start-cli s9pk publish` for uploading packages). Pass the registry's URL with `--registry`, using an address listed on its **Web API — _registry name_** interface: authenticated requests are signed for that hostname. It is a top-level flag, so it goes before the subcommand: ```sh -start-cli registry --registry https://my-registry.example.com index +start-cli --registry https://my-registry.example.com registry index ``` -If you're working inside a packaging workspace, add the registry to its `.startos/config.yaml` under `registry:` as a named profile, then refer to it with `-r `: +If you're working inside a packaging workspace, add the registry to its `.startos/config.yaml` under `registry:` as a named profile, then refer to it with `-r `, also placed before the subcommand: ```yaml registry: default: https://my-registry.example.com ``` -Now `start-cli registry -r default index` works, and because it's named `default` you can drop the flag entirely (`-r` uses the `default` profile when omitted). Outside a workspace, keep passing `--registry ` on each command. +Because it's named `default`, `start-cli registry index` now uses it with no flag. Give any other registry its own name and select it with `start-cli -r registry index`. Outside a workspace, keep passing `--registry ` on each command. ## 5. Smoke-test @@ -83,6 +87,6 @@ start-cli registry index start-cli registry admin list ``` -The first lists registry metadata and packages (empty on a fresh install). The second should show the administrator you added in step 3. If either fails, check that the service is running, the API interface is reachable from your workstation, and your identity key matches the public key you registered. +The first lists registry metadata and packages (empty on a fresh install). The second should show the administrator you added in step 3. If either fails, check that the service is running, the registry's **Web API — _registry name_** interface is reachable from your workstation, and your identity key matches the public key you registered. You're now ready to add signers, publish packages, and register StartOS versions. Before inviting users to connect, [select which signing keys your registry offers](host-registry-administration.md#offering-signing-keys-to-users). See [Administration](host-registry-administration.md) for these operations. From d10acf7baa527f7aa569e1f23408956a06f761cd Mon Sep 17 00:00:00 2001 From: "start9-docs-bot[bot]" <315476469+start9-docs-bot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:42:16 +0000 Subject: [PATCH 29/38] docs: backport live-docs ad1e6f489 to master Backports the following from live-docs: - ad1e6f489 docs(start-sdk): registry keeps only signatures from registered signers (#4815) --- .../docs/src/host-registry-administration.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/projects/start-sdk/docs/src/host-registry-administration.md b/projects/start-sdk/docs/src/host-registry-administration.md index 59ce3c1ac2..0e5a7c1096 100644 --- a/projects/start-sdk/docs/src/host-registry-administration.md +++ b/projects/start-sdk/docs/src/host-registry-administration.md @@ -23,9 +23,15 @@ The registry returns the signer's ID. Use that ID with `start-cli registry admin To grant a signer admin privileges (or revoke them), use `start-cli registry admin add ` / `... admin remove `. +A registry keeps a package signature only while its key belongs to a registered signer. Signatures from any other key are dropped when a package is indexed and on each startup. Register a key before you rely on the signatures it makes. + +The exception is a read-only registry configured with `mirror-of`: it preserves its upstream's signatures, including across restarts. Removing `mirror-of` enables signature pruning on the next startup. + +Revoking a key, with `admin signer edit --remove-key ` or by deleting its signer with `admin signer remove `, removes it from every signer that holds it and deletes its signatures from indexed packages. Adding the key back does not restore those signatures; [cosign](#cosigning) the affected versions again. + ## Offering signing keys to users -Registry 1.4.0 and start-cli 2.7.0 support selecting registered signers whose keys the registry offers to StartOS 0.4.1.2 and later. New and upgraded registries start with no selection; registering an administrator or authorizing a package publisher does not select them. +A registry can offer the keys of selected registered signers to the StartOS servers that connect it. It starts with no selection; registering an administrator or authorizing a package publisher does not select them. As an administrator, list your registered signers and use the [trust-signer selection command](/start-os/cli-reference.html#start-cli-registry-info-set-trust-signers-signer) to select their IDs. Each call replaces the entire selection; passing no IDs clears it. The registry offers all keys belonging to the selected signers, along with their names and contact details. Select the signers whose signatures users should accept, not every identity allowed to upload. @@ -58,9 +64,9 @@ start-cli s9pk publish myservice_1.2.0_x86_64.s9pk `publish` uploads the original file to the configured S3 bucket and adds its URL and identity-key endorsement to the configured registry index. Configure the S3 destination and registry before publishing. To index an already hosted file, use `start-cli registry package add --url `. -For package add and add-mirror, the CLI submits verified endorsements from `` separately from the authenticated uploader's signature. The registry verifies every submitted endorsement against the indexed package's exact Merkle root, signed bound, and `s9pk` context before adding it to the asset signature map. An invalid entry rejects the request atomically. The hosted file may contain only the base archive, and its bytes remain unchanged. Promotion forwards the indexed signature map to the destination registry. +For package add and add-mirror, the CLI submits verified endorsements from `` separately from the authenticated uploader's signature. The registry verifies every submitted endorsement against the indexed package's exact Merkle root, signed bound, and `s9pk` context before adding it to the asset signature map, then keeps only signatures from registered signers. An invalid entry rejects the request atomically. The hosted file may contain only the base archive, and its bytes remain unchanged. Promotion forwards the indexed signature map to the destination registry, which keeps only the signatures from its own registered signers. -Supplemental keys do not become registered signers, proposed trust keys, or authorized uploaders. Publishing authorization remains tied to the registered uploader. +Supplemental keys do not become registered signers, proposed trust keys, or authorized uploaders, so register a supplemental key as a signer if its endorsement should stay in the index. Publishing authorization remains tied to the registered uploader. ### Promoting a package From 0095c0e98ad88e02fe63d416f3bbe2618b2c7790 Mon Sep 17 00:00:00 2001 From: Helix the Red <355572797+helix-red@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:35:14 -0700 Subject: [PATCH 30/38] fix(ci): retry artifact listing pages GitHub fails transiently (#4812) GitHub intermittently answers the repository artifacts listing with an empty HTTP 500. Glob discovery reads about 110 pages of it per lookup, so one such answer failed every alpha apt publication since #4795 with 'unexpected end of JSON input'. Each page now retries up to five times with a growing delay before discovery fails. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --- scripts/gha-artifact-run-ids.sh | 15 ++++++++++++--- scripts/tests/gha-artifact-fixture.mjs | 14 ++++++++++++-- scripts/tests/gha-artifact-run-ids-test.mjs | 20 +++++++++++++++++--- 3 files changed, 41 insertions(+), 8 deletions(-) diff --git a/scripts/gha-artifact-run-ids.sh b/scripts/gha-artifact-run-ids.sh index 1af2c3b8a6..789b5752f9 100755 --- a/scripts/gha-artifact-run-ids.sh +++ b/scripts/gha-artifact-run-ids.sh @@ -10,10 +10,19 @@ repo=$1 glob=$2 branch=$3 declare -A seen=() +# One page of the listing. GitHub intermittently answers it with an empty 500. +list_page() { + local attempt + for attempt in 1 2 3 4 5; do + gh api "repos/$repo/actions/artifacts?per_page=100&page=$1" \ + --jq '.artifacts[] | [.name, .expired, .workflow_run.head_branch, .workflow_run.id, + ((.created_at | fromdateiso8601) < (now - 15 * 86400))] | @tsv' && return 0 + [ "$attempt" -eq 5 ] || sleep $((attempt * 5)) + done + return 1 +} for ((page = 1; ; page++)); do - rows=$(gh api "repos/$repo/actions/artifacts?per_page=100&page=$page" \ - --jq '.artifacts[] | [.name, .expired, .workflow_run.head_branch, .workflow_run.id, - ((.created_at | fromdateiso8601) < (now - 15 * 86400))] | @tsv') + rows=$(list_page "$page") [ -n "$rows" ] || break while IFS=$'\t' read -r name expired head_branch run_id stale; do [ "$stale" = false ] || exit 0 diff --git a/scripts/tests/gha-artifact-fixture.mjs b/scripts/tests/gha-artifact-fixture.mjs index 001154fdfa..eaed53486b 100644 --- a/scripts/tests/gha-artifact-fixture.mjs +++ b/scripts/tests/gha-artifact-fixture.mjs @@ -12,9 +12,10 @@ export function artifactFixture(t, runs) { f.write('runs.json', JSON.stringify(runs)) f.write('gh.log', '') f.write('downloads.log', '') + f.nodeExecutable('sleep', '') f.nodeExecutable( 'gh', - `import { appendFileSync, readFileSync } from 'node:fs' + `import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs' import { spawnSync } from 'node:child_process' const root = ${JSON.stringify(f.root)} const runs = JSON.parse(readFileSync(root + '/runs.json')) @@ -31,7 +32,16 @@ const newestFirst = (a, b) => b.created_at.localeCompare(a.created_at) || b.workflow_run.id - a.workflow_run.id if (args[0] === 'api') { const url = args.find(arg => arg.startsWith('repos/')) - if (process.env.GH_FAIL_MATCH && url.includes(process.env.GH_FAIL_MATCH)) process.exit(17) + if (process.env.GH_FAIL_MATCH && url.includes(process.env.GH_FAIL_MATCH)) { + // GH_FAIL_TIMES bounds the failures, shared across calls through a counter file. + const limit = Number(process.env.GH_FAIL_TIMES ?? Infinity) + const counter = root + '/gh-failures' + const failed = existsSync(counter) ? Number(readFileSync(counter, 'utf8')) : 0 + if (failed < limit) { + writeFileSync(counter, String(failed + 1)) + process.exit(17) + } + } const page = Number(new URL('https://x/' + url).searchParams.get('page') ?? 1) let response const workflow = url.match(/workflows\\/([^/]+)\\/runs/) diff --git a/scripts/tests/gha-artifact-run-ids-test.mjs b/scripts/tests/gha-artifact-run-ids-test.mjs index 49ccbefbbf..0f8ffa88c0 100644 --- a/scripts/tests/gha-artifact-run-ids-test.mjs +++ b/scripts/tests/gha-artifact-run-ids-test.mjs @@ -80,10 +80,24 @@ test('discovery stops paging at an artifact created over 15 days ago', t => { assert.equal(calls.length, 1) }) +test('artifact discovery retries a listing page GitHub fails transiently', t => { + const { result, calls } = discover( + t, + [run(1, 'master', [image('aaaaaaa')])], + { GH_FAIL_MATCH: '/actions/artifacts', GH_FAIL_TIMES: '2' }, + ) + assert.equal(result.status, 0, result.stdout + result.stderr) + assert.equal(result.stdout.trim(), '1') + assert.equal(calls.length, 4) +}) + test('artifact discovery propagates API failures', t => { - const { result } = discover(t, [run(1, 'master', [image('aaaaaaa')])], { - GH_FAIL_MATCH: '/actions/artifacts', - }) + const { result, calls } = discover( + t, + [run(1, 'master', [image('aaaaaaa')])], + { GH_FAIL_MATCH: '/actions/artifacts' }, + ) assert.notEqual(result.status, 0) assert.equal(result.stdout, '') + assert.equal(calls.length, 5) }) From 00a168b625f0ebf8972060e32556cec1d082ecc3 Mon Sep 17 00:00:00 2001 From: Dominion5254 Date: Thu, 19 Nov 2026 19:41:13 -0700 Subject: [PATCH 31/38] fix(ci): add swap to StartWRT riscv64 builds (#4803) Since 2026-11-16 the riscv64 build has been SIGKILLed while compiling start-core, on master and on unrelated PRs. Every kill ran on an AWS-hosted ubuntu-latest runner: 15.33 GiB of RAM and no swap, since the runner image only creates its 4 GiB swapfile through the Azure agent. Azure runners (15.61 GiB + 4 GiB swap) have not failed. The build peaks at about 13.2 GB of anonymous memory while start-core is still generating code and startwrt-core has already started. On an AWS runner that leaves little or no headroom. setup-build gains a swap-size input. start-wrt.yaml passes 8G to both jobs that compile the binary, including the OpenWrt image job, whose start-wrt-image target rebuilds it. --- .github/actions/setup-build/action.yml | 16 ++++++++++++++++ .github/workflows/start-wrt.yaml | 4 ++++ 2 files changed, 20 insertions(+) diff --git a/.github/actions/setup-build/action.yml b/.github/actions/setup-build/action.yml index 4f4d2567a8..b187b4d444 100644 --- a/.github/actions/setup-build/action.yml +++ b/.github/actions/setup-build/action.yml @@ -21,6 +21,10 @@ inputs: description: Remove unnecessary packages to free disk space required: false default: 'true' + swap-size: + description: Size of a swapfile to add, such as 8G; empty adds none + required: false + default: '' runs: using: composite @@ -30,6 +34,18 @@ runs: shell: bash run: '"$GITHUB_ACTION_PATH/free-disk-space.sh"' + - name: Add swap + if: inputs.swap-size != '' + shell: bash + env: + SWAP_SIZE: ${{ inputs.swap-size }} + run: | + sudo fallocate -l "$SWAP_SIZE" /swapfile-build + sudo chmod 600 /swapfile-build + sudo mkswap /swapfile-build + sudo swapon /swapfile-build + swapon --show + # Some runners lack /opt/hostedtoolcache, which setup-python and setup-qemu expect - name: Ensure hostedtoolcache exists shell: bash diff --git a/.github/workflows/start-wrt.yaml b/.github/workflows/start-wrt.yaml index c7aa72836b..7a11df5c6e 100644 --- a/.github/workflows/start-wrt.yaml +++ b/.github/workflows/start-wrt.yaml @@ -40,6 +40,8 @@ concurrency: env: NODEJS_VERSION: '24.17.0' + # Compiling the riscv64 binary outgrows the RAM of runners without swap. + BUILD_SWAP_SIZE: 8G jobs: changes: @@ -78,6 +80,7 @@ jobs: - uses: ./.github/actions/setup-build with: nodejs-version: ${{ env.NODEJS_VERSION }} + swap-size: ${{ env.BUILD_SWAP_SIZE }} - name: Make start-wrt run: make start-wrt @@ -133,6 +136,7 @@ jobs: - uses: ./.github/actions/setup-build with: nodejs-version: ${{ env.NODEJS_VERSION }} + swap-size: ${{ env.BUILD_SWAP_SIZE }} # Host deps for the OpenWrt build, restored from the old standalone # repo's setup-build action (the monorepo's shared setup-build serves From 158247471e21f18e8b8e92eb073155e66716b070 Mon Sep 17 00:00:00 2001 From: Matt Hill <9935159+MattDHill@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:43:29 -0700 Subject: [PATCH 32/38] fix(sdk): drop undeclared keys from action input (#4814) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(sdk): drop undeclared keys from action input An action's input was parsed with the built InputSpec validator, a z.looseObject at every level, so any key a caller submitted outside the form reached the handler. Packages that merge input into a file model whose formToFile spreads it (bitcoin-core's `raw`, cln's INI) then wrote those keys to disk. The web UI only submits declared fields, so only an admin's own RPC/CLI call could do it, but the handler should never see them. The validators InputSpec.build() and Variants build return, which only the action run path consumes, are now z.object, so unknown keys are stripped at every level, lists of objects and union values included. The static `validator` and `partialValidator` stay loose: file models are built from them and must keep keys their schema doesn't name. Co-Authored-By: Claude Opus 5.5 * fix(sdk): strip undeclared keys from union-history drafts A union's `other` carries the saved values of unselected variants, and its recognized entries were z.any(), so a draft such as `other.previous: { raw: { startupnotify: … } }` reached the handler intact. Each draft now parses through a deep-partial of its variant's built validator: undeclared keys go at every level, missing fields stay allowed, and a draft that fails to parse is dropped rather than failing the submission. Co-Authored-By: Claude Opus 5.5 * fix(sdk): carry only the selected variant in action input A union's `other` is the form's memory of unselected variants. The web UI keeps it in the union control and never submits it, and no handler reads it, yet the action validator parsed it. Validating that history meant running field transforms with side effects, such as resolving an upload, on drafts nobody will use. The validator an action runs its input through now keeps only `selection` and `value`. The static validators still accept `other`, for prefill and file models. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- ...h-security-action-input-undeclared-keys.md | 5 ++ .../lib/actions/input/builder/inputSpec.ts | 3 +- .../lib/actions/input/builder/variants.ts | 16 +--- .../lib/test/inputSpec.buildValidator.test.ts | 80 +++++++++++++++++++ 4 files changed, 88 insertions(+), 16 deletions(-) create mode 100644 projects/start-sdk/changelog/patch-security-action-input-undeclared-keys.md create mode 100644 shared-libs/ts-modules/start-core/lib/test/inputSpec.buildValidator.test.ts diff --git a/projects/start-sdk/changelog/patch-security-action-input-undeclared-keys.md b/projects/start-sdk/changelog/patch-security-action-input-undeclared-keys.md new file mode 100644 index 0000000000..423de639c9 --- /dev/null +++ b/projects/start-sdk/changelog/patch-security-action-input-undeclared-keys.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- An action's handler receives only the fields its input form declares; any other key in a submitted input is dropped, at every nesting level. A union field's input carries only its selected variant. diff --git a/shared-libs/ts-modules/start-core/lib/actions/input/builder/inputSpec.ts b/shared-libs/ts-modules/start-core/lib/actions/input/builder/inputSpec.ts index 3f4e20d2d7..f9ba7e98fb 100644 --- a/shared-libs/ts-modules/start-core/lib/actions/input/builder/inputSpec.ts +++ b/shared-libs/ts-modules/start-core/lib/actions/input/builder/inputSpec.ts @@ -221,6 +221,7 @@ export class InputSpec< deepPartial(this.validator) /** * Builds the runtime form specification and combined Zod validator from this InputSpec's fields. + * The validator drops every key the form doesn't declare; `validator` and `partialValidator` keep them, for file models. * * @returns An object containing the resolved `spec` (field specs keyed by name) and a combined `validator` */ @@ -243,7 +244,7 @@ export class InputSpec< } return { spec: answer, - validator: z.looseObject(validator) as any, + validator: z.object(validator) as any, } } diff --git a/shared-libs/ts-modules/start-core/lib/actions/input/builder/variants.ts b/shared-libs/ts-modules/start-core/lib/actions/input/builder/variants.ts index 06dccc78da..1effd5f65c 100644 --- a/shared-libs/ts-modules/start-core/lib/actions/input/builder/variants.ts +++ b/shared-libs/ts-modules/start-core/lib/actions/input/builder/variants.ts @@ -178,25 +178,11 @@ export class Variants< } validators[key] = built.validator } - const other = z - .looseObject( - Object.fromEntries( - Object.entries(validators).map(([k, v]) => [ - k, - z.any().optional(), - ]), - ), - ) - .optional() return { spec: variants, validator: z.union( Object.entries(validators).map(([k, v]) => - z.looseObject({ - selection: z.literal(k), - value: v, - other, - }), + z.object({ selection: z.literal(k), value: v }), ) as [z.ZodObject, z.ZodObject, ...z.ZodObject[]], ) as any, } diff --git a/shared-libs/ts-modules/start-core/lib/test/inputSpec.buildValidator.test.ts b/shared-libs/ts-modules/start-core/lib/test/inputSpec.buildValidator.test.ts new file mode 100644 index 0000000000..dcef292495 --- /dev/null +++ b/shared-libs/ts-modules/start-core/lib/test/inputSpec.buildValidator.test.ts @@ -0,0 +1,80 @@ +import { Effects } from '../Effects' +import { InputSpec } from '../actions/input/builder/inputSpec' +import { List } from '../actions/input/builder/list' +import { Value } from '../actions/input/builder/value' +import { Variants } from '../actions/input/builder/variants' + +const spec = InputSpec.of({ + rpc: Value.object( + { name: 'RPC' }, + InputSpec.of({ + port: Value.number({ + name: 'Port', + required: true, + default: 8332, + integer: true, + }), + }), + ), + mode: Value.union({ + name: 'Mode', + default: 'a', + variants: Variants.of({ + a: { + name: 'A', + spec: InputSpec.of({ x: Value.toggle({ name: 'X', default: false }) }), + }, + b: { name: 'B', spec: InputSpec.of({}) }, + }), + }), + peers: Value.list( + List.obj( + { name: 'Peers' }, + { + spec: InputSpec.of({ + host: Value.text({ name: 'Host', required: true, default: null }), + }), + }, + ), + ), +}) + +const submitted = { + rpc: { port: 1, rpcauth: 'injected' }, + mode: { selection: 'a', value: { x: true, y: 'injected' }, z: 'injected' }, + peers: [{ host: 'h', extra: 'injected' }], + raw: { startupnotify: 'injected' }, +} + +describe('the validator an action runs its input through', () => { + test('drops keys the form does not declare, at every level', async () => { + const { validator } = await spec.build({ + effects: {} as Effects, + prefill: null, + }) + expect(validator.parse(submitted)).toEqual({ + rpc: { port: 1 }, + mode: { selection: 'a', value: { x: true } }, + peers: [{ host: 'h' }], + }) + }) + + test('drops union history, which only the form keeps', async () => { + const { validator } = await Variants.of({ + selected: { name: 'Selected', spec: InputSpec.of({}) }, + previous: { name: 'Previous', spec }, + }).build({ effects: {} as Effects, prefill: null }) + expect( + await validator.parseAsync({ + selection: 'selected', + value: {}, + other: { previous: submitted }, + }), + ).toEqual({ selection: 'selected', value: {} }) + }) + + test('leaves the static validators keeping them, for file models', () => { + expect(spec.validator.parse(submitted)).toEqual(submitted) + expect(spec.partialValidator.parse(submitted)).toEqual(submitted) + }) +}) From 26dccefd204c38319dcb214e43a94e2228898fee Mon Sep 17 00:00:00 2001 From: sovsender <240553480+sovsender@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:31:54 -0500 Subject: [PATCH 33/38] feat(os): grant optical drives to service containers A package that sets `opticalDrives: true` gets the server's optical drives inside its container: the block node /dev/srN and the SCSI generic node /dev/sgN. Both are found from sysfs by SCSI type, never by a /dev glob, so a disk on the same controller is never exposed. Drives connected or removed while the service runs are attached or detached within a couple of seconds. mknod is split into a free-standing form so the poller can create nodes without borrowing the container. Co-Authored-By: Claude Sonnet 5.5 --- .../src/app/services/api.fixures.ts | 5 + .../changelog/minor-added-optical-drives.md | 5 + .../ui/src/app/services/api/api.fixures.ts | 16 ++ .../changelog/minor-added-optical-drives.md | 5 + projects/start-sdk/docs/src/manifest.md | 13 ++ .../start-sdk/lib/manifest/setupManifest.ts | 1 + shared-libs/crates/start-core/mcp-tools.json | 10 ++ .../crates/start-core/s9pk-structure.md | 1 + shared-libs/crates/start-core/src/lxc/mod.rs | 116 +++++++++++++- .../crates/start-core/src/lxc/optical.rs | 141 ++++++++++++++++++ .../start-core/src/net/static_server.rs | 1 + .../start-core/src/registry/package/get.rs | 1 + .../start-core/src/registry/package/index.rs | 4 + .../crates/start-core/src/s9pk/v2/compat.rs | 1 + .../crates/start-core/src/s9pk/v2/manifest.rs | 1 + .../src/service/persistent_container.rs | 1 + .../lib/osBindings/rpc/effects.schemas.ts | 11 ++ .../lib/osBindings/rpc/registry.schemas.ts | 11 ++ .../lib/osBindings/rpc/start-os.schemas.ts | 11 ++ .../lib/osBindings/types.schemas.ts | 11 ++ .../start-core/lib/types/ManifestTypes.ts | 6 + 21 files changed, 364 insertions(+), 8 deletions(-) create mode 100644 projects/start-os/changelog/minor-added-optical-drives.md create mode 100644 projects/start-sdk/changelog/minor-added-optical-drives.md create mode 100644 shared-libs/crates/start-core/src/lxc/optical.rs diff --git a/projects/brochure-marketplace/src/app/services/api.fixures.ts b/projects/brochure-marketplace/src/app/services/api.fixures.ts index a86266c6a8..e432f31ea7 100644 --- a/projects/brochure-marketplace/src/app/services/api.fixures.ts +++ b/projects/brochure-marketplace/src/app/services/api.fixures.ts @@ -165,6 +165,7 @@ For the full changelog, see https://github.com/bitcoin/bitcoin/blob/v27.0.0/doc/ userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, '#knots:27.1.0:0': { @@ -203,6 +204,7 @@ For the full changelog, see https://github.com/bitcoin/bitcoin/blob/v27.0.0/doc/ userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, }, @@ -254,6 +256,7 @@ For the full changelog, see https://github.com/bitcoin/bitcoin/blob/v27.0.0/doc/ userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, }, @@ -304,6 +307,7 @@ For the full changelog, see https://github.com/bitcoin/bitcoin/blob/v27.0.0/doc/ userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, '#test:0.5.0:0': { @@ -341,6 +345,7 @@ For the full changelog, see https://github.com/bitcoin/bitcoin/blob/v27.0.0/doc/ userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, }, diff --git a/projects/start-os/changelog/minor-added-optical-drives.md b/projects/start-os/changelog/minor-added-optical-drives.md new file mode 100644 index 0000000000..bf11fd6109 --- /dev/null +++ b/projects/start-os/changelog/minor-added-optical-drives.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Services can be granted the server's optical drives, including ones connected while the service runs, so disc-ripping apps work with a USB or SATA drive. diff --git a/projects/start-os/web/ui/src/app/services/api/api.fixures.ts b/projects/start-os/web/ui/src/app/services/api/api.fixures.ts index c4696f5e38..ba645b050c 100644 --- a/projects/start-os/web/ui/src/app/services/api/api.fixures.ts +++ b/projects/start-os/web/ui/src/app/services/api/api.fixures.ts @@ -387,6 +387,7 @@ export namespace Mock { userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], } @@ -444,6 +445,7 @@ export namespace Mock { userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], } @@ -487,6 +489,7 @@ export namespace Mock { userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: ['url-v0'], } @@ -537,6 +540,7 @@ export namespace Mock { userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], } @@ -609,6 +613,7 @@ export namespace Mock { userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, '#knots:26.1.20240325:0': { @@ -647,6 +652,7 @@ export namespace Mock { userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, }, @@ -695,6 +701,7 @@ export namespace Mock { userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, '#knots:26.1.20240325:0': { @@ -733,6 +740,7 @@ export namespace Mock { userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, }, @@ -786,6 +794,7 @@ export namespace Mock { userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, }, @@ -837,6 +846,7 @@ export namespace Mock { userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, }, @@ -889,6 +899,7 @@ export namespace Mock { userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, }, @@ -1013,6 +1024,7 @@ For the full changelog, see https://github.com/bitcoin/bitcoin/blob/v27.0.0/doc/ userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, '#knots:27.1.0:0': { @@ -1051,6 +1063,7 @@ For the full changelog, see https://github.com/bitcoin/bitcoin/blob/v27.0.0/doc/ userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, }, @@ -1102,6 +1115,7 @@ For the full changelog, see https://github.com/bitcoin/bitcoin/blob/v27.0.0/doc/ userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, }, @@ -1159,6 +1173,7 @@ Full changelog: https://github.com/Kixunil/btc-rpc-proxy/blob/master/CHANGELOG.m userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, '#test:0.5.0:0': { @@ -1196,6 +1211,7 @@ Full changelog: https://github.com/Kixunil/btc-rpc-proxy/blob/master/CHANGELOG.m userspaceFilesystems: false, virtualNetworking: false, hardwareVirtualization: false, + opticalDrives: false, plugins: [], }, }, diff --git a/projects/start-sdk/changelog/minor-added-optical-drives.md b/projects/start-sdk/changelog/minor-added-optical-drives.md new file mode 100644 index 0000000000..91098d2789 --- /dev/null +++ b/projects/start-sdk/changelog/minor-added-optical-drives.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Set `opticalDrives: true` in the manifest to grant a service the server's optical drives. The capability needs a StartOS release that supports it. diff --git a/projects/start-sdk/docs/src/manifest.md b/projects/start-sdk/docs/src/manifest.md index dd1eeb6f96..21cbce604d 100644 --- a/projects/start-sdk/docs/src/manifest.md +++ b/projects/start-sdk/docs/src/manifest.md @@ -350,6 +350,19 @@ When set, StartOS exposes `/dev/kvm` inside the service's container, so the gues > [!IMPORTANT] > The granted node belongs to the container's root and carries the permissions the server gives it, which on `/dev/kvm` are `0660`. **Run the process that opens it as root**, as the GPU packages do for `hardwareAcceleration` — that is the only arrangement StartOS guarantees. +### Optical Drives + +For services that read discs, such as ripping or archiving tools, set `opticalDrives: true` at the manifest top level: + +```typescript +opticalDrives: true, +``` + +When set, StartOS exposes the server's optical drives inside the service's container: the block node `/dev/srN` and its SCSI generic node `/dev/sgN`. A drive connected while the service runs appears within seconds, and the nodes of a drive that is disconnected are removed. Other disks, even on the same controller, are never exposed. + +> [!IMPORTANT] +> Like `/dev/kvm`, the nodes belong to the container's root with mode `0660`. **Run the process that opens them as root.** + The device appears only on a server whose CPU supports virtualization and whose kernel has KVM active for it. Where it does not, the service starts as normal with no `/dev/kvm` — so a service that can fall back to software emulation should test for the device and do so, and one that cannot should declare a health check saying this server does not support KVM. Give that check `gracePeriod: 0`, so it reports the reason instead of `starting`, and `sdk.trigger.onceTrigger` — the default re-polls a failing check every second for the life of the service. See [Health Checks](./main.md#health-checks). > [!WARNING] diff --git a/projects/start-sdk/lib/manifest/setupManifest.ts b/projects/start-sdk/lib/manifest/setupManifest.ts index 0301093174..ee7e1eb4c3 100644 --- a/projects/start-sdk/lib/manifest/setupManifest.ts +++ b/projects/start-sdk/lib/manifest/setupManifest.ts @@ -140,6 +140,7 @@ export function buildManifest< userspaceFilesystems: manifest.userspaceFilesystems ?? false, virtualNetworking: manifest.virtualNetworking ?? false, hardwareVirtualization: manifest.hardwareVirtualization ?? false, + opticalDrives: manifest.opticalDrives ?? false, sharedVolumes: manifest.sharedVolumes ?? false, plugins: manifest.plugins ?? [], } diff --git a/shared-libs/crates/start-core/mcp-tools.json b/shared-libs/crates/start-core/mcp-tools.json index 9fd256a9f3..b0488e641e 100644 --- a/shared-libs/crates/start-core/mcp-tools.json +++ b/shared-libs/crates/start-core/mcp-tools.json @@ -6748,6 +6748,10 @@ "description": "Grants /dev/kvm when present. The opening process must run as container root.", "type": "boolean" }, + "opticalDrives": { + "description": "Grants optical drives and their SCSI generic nodes, including ones plugged in later.", + "type": "boolean" + }, "plugins": { "type": "array", "items": { "$ref": "#/$defs/PluginId" } @@ -6773,6 +6777,7 @@ "userspaceFilesystems", "virtualNetworking", "hardwareVirtualization", + "opticalDrives", "plugins", "satisfies" ], @@ -9947,6 +9952,10 @@ "description": "Grants /dev/kvm when present. The opening process must run as container root.", "type": "boolean" }, + "opticalDrives": { + "description": "Grants optical drives and their SCSI generic nodes, including ones plugged in later.", + "type": "boolean" + }, "plugins": { "type": "array", "items": { "$ref": "#/$defs/PluginId" } @@ -9972,6 +9981,7 @@ "userspaceFilesystems", "virtualNetworking", "hardwareVirtualization", + "opticalDrives", "plugins", "satisfies" ], diff --git a/shared-libs/crates/start-core/s9pk-structure.md b/shared-libs/crates/start-core/s9pk-structure.md index 829bff27b9..37f10db609 100644 --- a/shared-libs/crates/start-core/s9pk-structure.md +++ b/shared-libs/crates/start-core/s9pk-structure.md @@ -88,6 +88,7 @@ The package manifest contains all metadata: | `userspaceFilesystems` | boolean | Whether package is granted `/dev/fuse` | | `virtualNetworking` | boolean | Whether package is granted `/dev/net/tun` | | `hardwareVirtualization` | boolean | Whether package is granted `/dev/kvm` | +| `opticalDrives` | boolean | Whether package is granted the optical drives | | `plugins` | string[] | Plugin IDs the package registers | | `gitHash` | string? | Git commit hash | | `osVersion` | string | Minimum StartOS version | diff --git a/shared-libs/crates/start-core/src/lxc/mod.rs b/shared-libs/crates/start-core/src/lxc/mod.rs index 8503ba0603..9defb11d92 100644 --- a/shared-libs/crates/start-core/src/lxc/mod.rs +++ b/shared-libs/crates/start-core/src/lxc/mod.rs @@ -27,12 +27,14 @@ use crate::disk::mount::util::unmount; use crate::prelude::*; use crate::rpc_continuations::{Guid, RpcContinuation, WebSocketPolicy}; use crate::service::ServiceStats; +use crate::util::future::NonDetachingJoinHandle; use crate::util::io::{open_file, write_file_owned_atomic}; use crate::util::rpc_client::UnixRpcClient; use crate::util::{FromStrParser, Invoke, new_guid}; use crate::{InvalidId, PackageId}; mod filesystem; +mod optical; pub(crate) use filesystem::{BASE_IDMAP, service_filesystem, unshifted_filesystem}; @@ -56,6 +58,7 @@ const HARDWARE_ACCELERATION_PATHS: &[&str] = &["/dev/dri", "/dev/nvidia*", "/dev const USERSPACE_FILESYSTEM_PATHS: &[&str] = &["/dev/fuse"]; const VIRTUAL_NETWORKING_PATHS: &[&str] = &["/dev/net/tun"]; const HARDWARE_VIRTUALIZATION_PATHS: &[&str] = &["/dev/kvm"]; +const OPTICAL_DRIVE_POLL_INTERVAL: Duration = Duration::from_secs(2); #[cfg(all(test, target_os = "linux"))] mod gc_tests; @@ -240,6 +243,7 @@ pub struct LxcContainer { rpc_bind: TmpMountGuard, log_mount: Option, config: LxcConfig, + optical_drives: Option>, exited: bool, } impl LxcContainer { @@ -350,12 +354,13 @@ impl LxcContainer { .arg("DEBUG") .invoke(ErrorKind::Lxc) .await?; - let res = Self { + let mut res = Self { manager: Arc::downgrade(manager), rootfs, guid: Arc::new(ContainerId::try_from(&*guid)?), rpc_bind, config, + optical_drives: None, exited: false, log_mount, }; @@ -368,9 +373,31 @@ impl LxcContainer { ) .await?; } + if res.config.optical_drives { + res.optical_drives = Some(res.track_optical_drives().await); + } Ok(res) } + async fn track_optical_drives(&self) -> NonDetachingJoinHandle<()> { + let guid = self.guid.clone(); + let rootfs = self.rootfs_dir().to_path_buf(); + let mut applied = BTreeSet::new(); + if let Err(e) = sync_optical_drives(&**guid, &rootfs, &mut applied).await { + tracing::warn!("optical drives for {}: {e}", &**guid); + tracing::debug!("{e:?}"); + } + tokio::spawn(async move { + loop { + tokio::time::sleep(OPTICAL_DRIVE_POLL_INTERVAL).await; + if let Err(e) = sync_optical_drives(&**guid, &rootfs, &mut applied).await { + tracing::debug!("optical drives for {}: {e:?}", &**guid); + } + } + }) + .into() + } + #[cfg(not(target_os = "linux"))] async fn handle_devices(&self, _: ReadDir, _: &[&str]) -> Result<(), Error> { Ok(()) @@ -531,6 +558,7 @@ impl LxcContainer { #[instrument(skip_all)] pub async fn exit(mut self) -> Result<(), Error> { + self.optical_drives.take(); Command::new("lxc-stop") .arg("--name") .arg(&**self.guid) @@ -591,12 +619,24 @@ impl LxcContainer { major: u32, minor: u32, mode: u32, + ) -> Result<(), Error> { + Self::mknod_in(&**self.guid, self.rootfs_dir(), path, ty, major, minor, mode).await + } + + async fn mknod_in( + guid: &str, + rootfs: &Path, + path: &Path, + ty: char, + major: u32, + minor: u32, + mode: u32, ) -> Result<(), Error> { // -m so the node carries the host's mode instead of `0666 & ~umask(startd)`. let mode = format!("{mode:04o}"); if let Ok(dev_rel) = path.strip_prefix("/dev") { let parent = dev_rel.parent(); - let media_dev = self.rootfs_dir().join("media/startos/dev"); + let media_dev = rootfs.join("media/startos/dev"); let target_path = media_dev.join(dev_rel); if tokio::fs::metadata(&target_path).await.is_ok() { return Ok(()); @@ -630,7 +670,7 @@ impl LxcContainer { .await?; if let Some(parent) = parent { Command::new("lxc-attach") - .arg(&**self.guid) + .arg(guid) .arg("--") .arg("mkdir") .arg("-p") @@ -639,14 +679,14 @@ impl LxcContainer { .await?; } Command::new("lxc-attach") - .arg(&**self.guid) + .arg(guid) .arg("--") .arg("touch") .arg(&path) .invoke(ErrorKind::Lxc) .await?; Command::new("lxc-attach") - .arg(&**self.guid) + .arg(guid) .arg("--") .arg("mount") .arg("--bind") @@ -655,9 +695,7 @@ impl LxcContainer { .invoke(ErrorKind::Lxc) .await?; } else { - let target_path = self - .rootfs_dir() - .join(path.strip_prefix("/").unwrap_or(&path)); + let target_path = rootfs.join(path.strip_prefix("/").unwrap_or(&path)); if tokio::fs::metadata(&target_path).await.is_ok() { return Ok(()); } @@ -679,6 +717,66 @@ impl LxcContainer { Ok(()) } } + +async fn sync_optical_drives( + guid: &str, + rootfs: &Path, + applied: &mut BTreeSet, +) -> Result<(), Error> { + let desired = optical::scan(Path::new("/sys")).await; + let removed = applied.difference(&desired).cloned().collect::>(); + for node in removed { + detach_node(guid, rootfs, &node.path).await?; + applied.remove(&node); + } + let added = desired.difference(applied).cloned().collect::>(); + for node in added { + if let Err(e) = LxcContainer::mknod_in( + guid, + rootfs, + &node.path, + node.ty, + node.major, + node.minor, + 0o660, + ) + .await + { + detach_node(guid, rootfs, &node.path).await.log_err(); + return Err(e); + } + applied.insert(node); + } + Ok(()) +} + +async fn detach_node(guid: &str, rootfs: &Path, path: &Path) -> Result<(), Error> { + let Ok(dev_rel) = path.strip_prefix("/dev") else { + return Ok(()); + }; + Command::new("lxc-attach") + .arg(guid) + .arg("--") + .arg("umount") + .arg("-l") + .arg(path) + .invoke(ErrorKind::Lxc) + .await + .log_err(); + Command::new("lxc-attach") + .arg(guid) + .arg("--") + .arg("rm") + .arg("-f") + .arg(path) + .invoke(ErrorKind::Lxc) + .await?; + match tokio::fs::remove_file(rootfs.join("media/startos/dev").join(dev_rel)).await { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()), + _ => Ok(()), + } +} + impl Drop for LxcContainer { fn drop(&mut self) { if !self.exited { @@ -738,6 +836,7 @@ pub struct LxcConfig { pub userspace_filesystems: bool, pub virtual_networking: bool, pub hardware_virtualization: bool, + pub optical_drives: bool, } impl LxcConfig { fn granted_device_paths(&self) -> Vec<&'static [&'static str]> { @@ -912,6 +1011,7 @@ mod test { userspace_filesystems: true, virtual_networking: true, hardware_virtualization: true, + optical_drives: true, }; assert_eq!( config.granted_device_paths(), diff --git a/shared-libs/crates/start-core/src/lxc/optical.rs b/shared-libs/crates/start-core/src/lxc/optical.rs new file mode 100644 index 0000000000..81ed3e04ea --- /dev/null +++ b/shared-libs/crates/start-core/src/lxc/optical.rs @@ -0,0 +1,141 @@ +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; + +const SCSI_TYPE_MMC: &str = "5"; + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct OpticalNode { + pub path: PathBuf, + pub ty: char, + pub major: u32, + pub minor: u32, +} + +fn parse_devt(raw: &str) -> Option<(u32, u32)> { + let (major, minor) = raw.trim().split_once(':')?; + Some((major.parse().ok()?, minor.parse().ok()?)) +} + +async fn read_trimmed(path: impl AsRef) -> Option { + tokio::fs::read_to_string(path) + .await + .ok() + .map(|s| s.trim().to_owned()) +} + +/// The block and SCSI-generic nodes of every optical drive under `sys`. +pub async fn scan(sys: &Path) -> BTreeSet { + let mut nodes = BTreeSet::new(); + let Ok(mut blocks) = tokio::fs::read_dir(sys.join("class/block")).await else { + return nodes; + }; + while let Ok(Some(entry)) = blocks.next_entry().await { + let name = entry.file_name(); + if !name.to_string_lossy().starts_with("sr") { + continue; + } + let dir = entry.path(); + if read_trimmed(dir.join("device/type")).await.as_deref() != Some(SCSI_TYPE_MMC) { + continue; + } + let Some((major, minor)) = read_trimmed(dir.join("dev")) + .await + .as_deref() + .and_then(parse_devt) + else { + continue; + }; + nodes.insert(OpticalNode { + path: Path::new("/dev").join(&name), + ty: 'b', + major, + minor, + }); + let Ok(mut generic) = tokio::fs::read_dir(dir.join("device/scsi_generic")).await else { + continue; + }; + while let Ok(Some(sg)) = generic.next_entry().await { + let sg_name = sg.file_name(); + let Some((major, minor)) = + read_trimmed(sys.join("class/scsi_generic").join(&sg_name).join("dev")) + .await + .as_deref() + .and_then(parse_devt) + else { + continue; + }; + nodes.insert(OpticalNode { + path: Path::new("/dev").join(&sg_name), + ty: 'c', + major, + minor, + }); + } + } + nodes +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write(root: &Path, rel: &str, contents: &str) { + let path = root.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, contents).unwrap(); + } + + fn node(path: &str, ty: char, major: u32, minor: u32) -> OpticalNode { + OpticalNode { + path: PathBuf::from(path), + ty, + major, + minor, + } + } + + #[test] + fn parses_major_and_minor() { + assert_eq!(parse_devt("11:0\n"), Some((11, 0))); + assert_eq!(parse_devt("259:12"), Some((259, 12))); + assert_eq!(parse_devt("11"), None); + assert_eq!(parse_devt("a:b"), None); + } + + #[tokio::test] + async fn finds_the_drive_and_its_generic_node() { + let sys = tempfile::tempdir().unwrap(); + let root = sys.path(); + write(root, "class/block/sr0/dev", "11:0\n"); + write(root, "class/block/sr0/device/type", "5\n"); + write(root, "class/block/sr0/device/scsi_generic/sg1/.keep", ""); + write(root, "class/scsi_generic/sg1/dev", "21:1\n"); + + assert_eq!( + scan(root).await, + BTreeSet::from([node("/dev/sr0", 'b', 11, 0), node("/dev/sg1", 'c', 21, 1)]) + ); + } + + #[tokio::test] + async fn ignores_disks_and_non_optical_scsi_devices() { + let sys = tempfile::tempdir().unwrap(); + let root = sys.path(); + write(root, "class/block/sda/dev", "8:0\n"); + write(root, "class/block/sda/device/type", "0\n"); + write(root, "class/block/sda/device/scsi_generic/sg0/.keep", ""); + write(root, "class/scsi_generic/sg0/dev", "21:0\n"); + write(root, "class/block/sr1/dev", "11:1\n"); + write(root, "class/block/sr1/device/type", "0\n"); + write(root, "class/block/sr1/device/scsi_generic/sg2/.keep", ""); + write(root, "class/scsi_generic/sg2/dev", "21:2\n"); + + assert!(scan(root).await.is_empty()); + } + + #[tokio::test] + async fn a_missing_sysfs_yields_no_drives() { + let sys = tempfile::tempdir().unwrap(); + assert!(scan(&sys.path().join("absent")).await.is_empty()); + } +} diff --git a/shared-libs/crates/start-core/src/net/static_server.rs b/shared-libs/crates/start-core/src/net/static_server.rs index b510397c19..0c5f32cd75 100644 --- a/shared-libs/crates/start-core/src/net/static_server.rs +++ b/shared-libs/crates/start-core/src/net/static_server.rs @@ -1585,6 +1585,7 @@ mod tests { "userspaceFilesystems": false, "virtualNetworking": false, "hardwareVirtualization": false, + "opticalDrives": false, "plugins": [], "satisfies": [], "images": {}, diff --git a/shared-libs/crates/start-core/src/registry/package/get.rs b/shared-libs/crates/start-core/src/registry/package/get.rs index d9c29f5c18..184e2648cd 100644 --- a/shared-libs/crates/start-core/src/registry/package/get.rs +++ b/shared-libs/crates/start-core/src/registry/package/get.rs @@ -898,6 +898,7 @@ fn check_matching_info_short() { userspace_filesystems: false, virtual_networking: false, hardware_virtualization: false, + optical_drives: false, plugins: BTreeSet::new(), satisfies: BTreeSet::new(), }, diff --git a/shared-libs/crates/start-core/src/registry/package/index.rs b/shared-libs/crates/start-core/src/registry/package/index.rs index 2581bcde6e..05ae28f82a 100644 --- a/shared-libs/crates/start-core/src/registry/package/index.rs +++ b/shared-libs/crates/start-core/src/registry/package/index.rs @@ -271,6 +271,9 @@ pub struct PackageMetadata { /// Grants /dev/kvm when present. The opening process must run as container root. #[serde(default)] pub hardware_virtualization: bool, + /// Grants optical drives and their SCSI generic nodes, including ones plugged in later. + #[serde(default)] + pub optical_drives: bool, #[serde(default)] pub plugins: BTreeSet, #[serde(default)] @@ -700,6 +703,7 @@ pub(crate) mod tests { userspace_filesystems: false, virtual_networking: false, hardware_virtualization: true, + optical_drives: false, plugins: BTreeSet::new(), satisfies: BTreeSet::new(), }; diff --git a/shared-libs/crates/start-core/src/s9pk/v2/compat.rs b/shared-libs/crates/start-core/src/s9pk/v2/compat.rs index f5c7266455..b59c246ab3 100644 --- a/shared-libs/crates/start-core/src/s9pk/v2/compat.rs +++ b/shared-libs/crates/start-core/src/s9pk/v2/compat.rs @@ -274,6 +274,7 @@ impl TryFrom for Manifest { userspace_filesystems: false, virtual_networking: false, hardware_virtualization: false, + optical_drives: false, plugins: BTreeSet::new(), satisfies: BTreeSet::new(), }, diff --git a/shared-libs/crates/start-core/src/s9pk/v2/manifest.rs b/shared-libs/crates/start-core/src/s9pk/v2/manifest.rs index eb0e04160e..49c5869a1c 100644 --- a/shared-libs/crates/start-core/src/s9pk/v2/manifest.rs +++ b/shared-libs/crates/start-core/src/s9pk/v2/manifest.rs @@ -509,6 +509,7 @@ fn legacy_emulation_uses_the_image_kept_in_a_cross_arch_backup() { "userspaceFilesystems": false, "virtualNetworking": false, "hardwareVirtualization": false, + "opticalDrives": false, "plugins": [], "satisfies": [], "images": { diff --git a/shared-libs/crates/start-core/src/service/persistent_container.rs b/shared-libs/crates/start-core/src/service/persistent_container.rs index a8b1862820..38cd652fc0 100644 --- a/shared-libs/crates/start-core/src/service/persistent_container.rs +++ b/shared-libs/crates/start-core/src/service/persistent_container.rs @@ -156,6 +156,7 @@ impl PersistentContainer { userspace_filesystems: s9pk.manifest.metadata.userspace_filesystems, virtual_networking: s9pk.manifest.metadata.virtual_networking, hardware_virtualization: s9pk.manifest.metadata.hardware_virtualization, + optical_drives: s9pk.manifest.metadata.optical_drives, }, ) .await?; diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/effects.schemas.ts b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/effects.schemas.ts index 8d63856935..0f24e04b8f 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/effects.schemas.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/effects.schemas.ts @@ -2390,6 +2390,10 @@ export const PackageMetadata: z.ZodObject<{ * Grants /dev/kvm when present. The opening process must run as container root. */ hardwareVirtualization: z.ZodCodec, z.ZodBoolean> + /** + * Grants optical drives and their SCSI generic nodes, including ones plugged in later. + */ + opticalDrives: z.ZodCodec, z.ZodBoolean> plugins: z.ZodCodec< z.ZodOptional>, z.ZodArray @@ -2438,6 +2442,13 @@ export const PackageMetadata: z.ZodObject<{ description: 'Grants /dev/kvm when present. The opening process must run as container root.', }), + /** + * Grants optical drives and their SCSI generic nodes, including ones plugged in later. + */ + opticalDrives: wire(z.boolean().optional(), z.boolean()).meta({ + description: + 'Grants optical drives and their SCSI generic nodes, including ones plugged in later.', + }), plugins: wire(z.array(PluginId).optional(), z.array(PluginId)), satisfies: wire(z.array(Version).optional(), z.array(Version)), }).meta({ diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/registry.schemas.ts b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/registry.schemas.ts index 449334f180..3751e37082 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/registry.schemas.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/registry.schemas.ts @@ -1541,6 +1541,10 @@ export const PackageMetadata: z.ZodObject<{ * Grants /dev/kvm when present. The opening process must run as container root. */ hardwareVirtualization: z.ZodCodec, z.ZodBoolean> + /** + * Grants optical drives and their SCSI generic nodes, including ones plugged in later. + */ + opticalDrives: z.ZodCodec, z.ZodBoolean> plugins: z.ZodCodec< z.ZodOptional>, z.ZodArray @@ -1589,6 +1593,13 @@ export const PackageMetadata: z.ZodObject<{ description: 'Grants /dev/kvm when present. The opening process must run as container root.', }), + /** + * Grants optical drives and their SCSI generic nodes, including ones plugged in later. + */ + opticalDrives: wire(z.boolean().optional(), z.boolean()).meta({ + description: + 'Grants optical drives and their SCSI generic nodes, including ones plugged in later.', + }), plugins: wire(z.array(PluginId).optional(), z.array(PluginId)), satisfies: wire(z.array(Version).optional(), z.array(Version)), }).meta({ diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.schemas.ts b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.schemas.ts index 959346efe8..d562a4dd6b 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.schemas.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.schemas.ts @@ -5251,6 +5251,10 @@ export const PackageMetadata: z.ZodObject<{ * Grants /dev/kvm when present. The opening process must run as container root. */ hardwareVirtualization: z.ZodCodec, z.ZodBoolean> + /** + * Grants optical drives and their SCSI generic nodes, including ones plugged in later. + */ + opticalDrives: z.ZodCodec, z.ZodBoolean> plugins: z.ZodCodec< z.ZodOptional>, z.ZodArray @@ -5299,6 +5303,13 @@ export const PackageMetadata: z.ZodObject<{ description: 'Grants /dev/kvm when present. The opening process must run as container root.', }), + /** + * Grants optical drives and their SCSI generic nodes, including ones plugged in later. + */ + opticalDrives: wire(z.boolean().optional(), z.boolean()).meta({ + description: + 'Grants optical drives and their SCSI generic nodes, including ones plugged in later.', + }), plugins: wire(z.array(PluginId).optional(), z.array(PluginId)), satisfies: wire(z.array(Version).optional(), z.array(Version)), }).meta({ diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts b/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts index 97f5bb262c..a0ca819845 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts @@ -5781,6 +5781,10 @@ export const PackageMetadata: z.ZodObject<{ * Grants /dev/kvm when present. The opening process must run as container root. */ hardwareVirtualization: z.ZodCodec, z.ZodBoolean> + /** + * Grants optical drives and their SCSI generic nodes, including ones plugged in later. + */ + opticalDrives: z.ZodCodec, z.ZodBoolean> plugins: z.ZodCodec< z.ZodOptional>, z.ZodArray @@ -5829,6 +5833,13 @@ export const PackageMetadata: z.ZodObject<{ description: 'Grants /dev/kvm when present. The opening process must run as container root.', }), + /** + * Grants optical drives and their SCSI generic nodes, including ones plugged in later. + */ + opticalDrives: wire(z.boolean().optional(), z.boolean()).meta({ + description: + 'Grants optical drives and their SCSI generic nodes, including ones plugged in later.', + }), plugins: wire(z.array(PluginId).optional(), z.array(PluginId)), satisfies: wire(z.array(Version).optional(), z.array(Version)), }).meta({ diff --git a/shared-libs/ts-modules/start-core/lib/types/ManifestTypes.ts b/shared-libs/ts-modules/start-core/lib/types/ManifestTypes.ts index 2324c0444b..5072879229 100644 --- a/shared-libs/ts-modules/start-core/lib/types/ManifestTypes.ts +++ b/shared-libs/ts-modules/start-core/lib/types/ManifestTypes.ts @@ -146,6 +146,12 @@ export type SDKManifest = { */ readonly hardwareVirtualization?: boolean + /** + * @description Grants optical drives and their SCSI generic nodes, including ones plugged in + * later. + */ + readonly opticalDrives?: boolean + /** Enables user grants of shared volumes; opting in grants no access automatically. */ readonly sharedVolumes?: T.Manifest['sharedVolumes'] From c949d13794e0b53b6d25a25b73a0e50728e3db9e Mon Sep 17 00:00:00 2001 From: sovsender <240553480+sovsender@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:00:14 -0500 Subject: [PATCH 34/38] style(os): match rustfmt output in lxc Co-Authored-By: Claude Sonnet 5.5 --- shared-libs/crates/start-core/src/lxc/mod.rs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/shared-libs/crates/start-core/src/lxc/mod.rs b/shared-libs/crates/start-core/src/lxc/mod.rs index 9defb11d92..f8bf4e2612 100644 --- a/shared-libs/crates/start-core/src/lxc/mod.rs +++ b/shared-libs/crates/start-core/src/lxc/mod.rs @@ -620,7 +620,16 @@ impl LxcContainer { minor: u32, mode: u32, ) -> Result<(), Error> { - Self::mknod_in(&**self.guid, self.rootfs_dir(), path, ty, major, minor, mode).await + Self::mknod_in( + &**self.guid, + self.rootfs_dir(), + path, + ty, + major, + minor, + mode, + ) + .await } async fn mknod_in( @@ -732,13 +741,7 @@ async fn sync_optical_drives( let added = desired.difference(applied).cloned().collect::>(); for node in added { if let Err(e) = LxcContainer::mknod_in( - guid, - rootfs, - &node.path, - node.ty, - node.major, - node.minor, - 0o660, + guid, rootfs, &node.path, node.ty, node.major, node.minor, 0o660, ) .await { From 63a33ed1271c8c66a6267d7f8ad17fe79dc807f9 Mon Sep 17 00:00:00 2001 From: Dominion5254 Date: Thu, 19 Nov 2026 21:16:33 -0700 Subject: [PATCH 35/38] fix(core): keep a range's public IP on with its plain public domain across a renumber (#4666) * fix(core): keep a public-IP opt-in across a gateway renumber or link drop A public IP's opt-in is stored as the literal `ip:port` in `enabled` (and a GUA's in `gua_wan`), and nothing moved it when the address changed. A rolled DHCP lease, a moved IPv6 prefix, or a PPPoE reconnect therefore brought the replacement up switched off, dropped its port forward, and said nothing. master's plain-domain grouping (#4616) carries the setting only for a plain port with a public domain on the same gateway; a bare public `ip:port` had no such cover. `migrate_renumbered_ips` runs in `derive_addresses` for single-port bindings and ranges. Where a gateway offered exactly one public address on a port and family before and after, an opt-in on the old address extends to the new one. The old address keeps its opt-in while another row still offers it, so a server dual-homed on one router keeps the address its other link holds. A gateway NetworkManager drops has its `ip_info` cleared, and its rows used to leave `available` with it, so a gateway that came back on a new lease had no previous address to carry from. `carry_forward` keeps a downed gateway's public IPv4 and GUA rows until it returns or is deleted. Port forwards still need the live gateway and lapse while it is down. Split from #3999, without its manual WAN IP override. * Proposed changes for #4666 Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol * fix(core): keep a GUA opt-in until the reconnected gateway reports a GUA The first ip_info after a link drop can carry DHCPv4 before SLAAC: poll_ip_info publishes on every address change. carry_forward now keeps a gateway's GUA rows until it reports a GUA, mirroring the public IPv4 rule, so the renumber migration still finds the old address when the new one arrives. * revert(core): drop the renumber migration ahead of gateway-keyed public opt-ins Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(core): key public IP opt-ins by gateway so they survive a renumber Store a public IPv4 opt-in as (gateway, port) and a GUA opt-in as (gateway, port, interface identifier) instead of the literal WAN ip:port. The opt-in resolves against whatever address the gateway currently reports, so a new DHCP lease, a moved IPv6 prefix or a link drop no longer switches the address and its port forward off. - DerivedAddressInfo.enabled and gua_wan hold PublicIpKey. - 0.4.3's migration (revision 1) rewrites stored socket-address opt-ins as the keys of the rows they select, dropping unmatched ones. - forget_gateway drops every opt-in keyed to the removed gateway. - start-core TS gains publicIpKey/samePublicIpKey; the legacy projection still accepts socket-address strings from servers without `effective`. - Regenerated TS bindings and MCP catalog; UI mock data uses the keys. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * feat(start-os): mark IPv6 addresses whose opt-in switches together A GUA opt-in keys on its interface identifier, so every GUA on the gateway and port with that identifier (another prefix, or the old prefix during a renumber) switches with it. The gateway table now marks such rows with a link icon whose tooltip says so. The UI derives GUA-ness from start-core's publicIpKey instead of its own parser. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * docs(start-os): explain that IPv6 settings follow the interface ID Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(core): keep legacy getHostInfo readers and every gateway's opt-in - getHostInfo serves `enabled` as socket addresses, the form SDKs before `effective` match, for bindings and port ranges alike. - The 0.4.3 upgrade keys an opt-in on every row it selects, so a WAN IP two gateways share stays on for both; one unreadable row no longer drops a binding's opt-ins. - Forgetting an interface drops its selections through the same Model::forget_gateway the tunnel removal uses. - The link icon, docs and changelog name only the Local/Public choice and the toggle while Public as shared. Co-authored-by: helix-white Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(core): keep a range's public IP on with its plain public domain Drop the gateway-keyed public opt-ins: a public IP opt-in stays the literal ip:port, and an operator who needs a stable public address uses a public domain with DDNS. On a plain port, an enabled public domain already carries its gateway's public IPv4 and GUA across a renumber for single-port bindings. update_addresses never re-resolved those groups for port ranges, so a range's public IP stayed off after a link drop or new lease. Resolve them for ranges too. Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * docs(core): record that a public IP opt-in lapses on a renumber Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(core): keep a renumbered range's plain domain on through the upgrade Released versions never resolved plain-domain groups for ranges, so a range renumbered before the upgrade holds an enabled plain domain beside an off WAN IP. Resolving its group from that state would switch the domain off. 0.4.3 (migration revision 1) switches on the group of each enabled plain public domain on a range first. Co-authored-by: helix-white Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --------- Co-authored-by: helix-a <267227783+helix-a@users.noreply.github.com> Co-authored-by: helix-red <355572797+helix-red@users.noreply.github.com> Co-authored-by: helix-white --- .../patch-fixed-range-domain-renumber.md | 5 + shared-libs/crates/start-core/mcp-tools.json | 4 +- .../crates/start-core/src/net/host/binding.rs | 2 + .../crates/start-core/src/net/host/mod.rs | 306 +++++++++++++++++- .../crates/start-core/src/version/mod.rs | 7 +- .../crates/start-core/src/version/v0_4_3.rs | 126 +++++++- .../lib/osBindings/rpc/effects.schemas.ts | 6 +- .../lib/osBindings/rpc/start-os.schemas.ts | 6 +- .../lib/osBindings/types.schemas.ts | 6 +- 9 files changed, 459 insertions(+), 9 deletions(-) create mode 100644 projects/start-os/changelog/patch-fixed-range-domain-renumber.md diff --git a/projects/start-os/changelog/patch-fixed-range-domain-renumber.md b/projects/start-os/changelog/patch-fixed-range-domain-renumber.md new file mode 100644 index 0000000000..1916b216bd --- /dev/null +++ b/projects/start-os/changelog/patch-fixed-range-domain-renumber.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- A port range's public IP address stays enabled with its plain public domain when the gateway's public IP changes, as it already did for single-port interfaces. diff --git a/shared-libs/crates/start-core/mcp-tools.json b/shared-libs/crates/start-core/mcp-tools.json index 9fd256a9f3..1a8afd16ab 100644 --- a/shared-libs/crates/start-core/mcp-tools.json +++ b/shared-libs/crates/start-core/mcp-tools.json @@ -4357,7 +4357,7 @@ "enabled": { "type": "array", "items": { "type": "string" }, - "description": "User override: enable these addresses (only for public IP & port)" + "description": "User override: enable these addresses (only for public IP & port)\nAn opt-in names one literal address and lapses when the gateway renumbers.\nOnly an enabled plain public domain carries its group's public IPs across." }, "disabled": { "type": "array", @@ -11108,7 +11108,7 @@ "enabled": { "type": "array", "items": { "type": "string" }, - "description": "User override: enable these addresses (only for public IP & port)" + "description": "User override: enable these addresses (only for public IP & port)\nAn opt-in names one literal address and lapses when the gateway renumbers.\nOnly an enabled plain public domain carries its group's public IPs across." }, "disabled": { "type": "array", diff --git a/shared-libs/crates/start-core/src/net/host/binding.rs b/shared-libs/crates/start-core/src/net/host/binding.rs index 63b536dddb..8c2b907cc3 100644 --- a/shared-libs/crates/start-core/src/net/host/binding.rs +++ b/shared-libs/crates/start-core/src/net/host/binding.rs @@ -64,6 +64,8 @@ impl FromStr for BindId { #[model = "Model"] pub struct DerivedAddressInfo { /// User override: enable these addresses (only for public IP & port) + /// An opt-in names one literal address and lapses when the gateway renumbers. + /// Only an enabled plain public domain carries its group's public IPs across. pub enabled: BTreeSet, /// User override: disable these addresses (only for domains and private IP & port) pub disabled: BTreeSet<(InternedString, u16)>, diff --git a/shared-libs/crates/start-core/src/net/host/mod.rs b/shared-libs/crates/start-core/src/net/host/mod.rs index dc0e100807..c7384a6049 100644 --- a/shared-libs/crates/start-core/src/net/host/mod.rs +++ b/shared-libs/crates/start-core/src/net/host/mod.rs @@ -160,6 +160,7 @@ impl Model { available_ports: &AvailablePorts, ) -> Result<(), Error> { let previous = self.as_bindings().de()?; + let previous_ranges = self.as_binding_ranges().de()?; self.derive_addresses(mdns, gateways, available_ports)?; self.as_bindings_mut().mutate(|bindings| { for (port, binding) in bindings.iter_mut() { @@ -170,6 +171,15 @@ impl Model { } Ok(()) })?; + self.as_binding_ranges_mut().mutate(|ranges| { + for (port, range) in ranges.iter_mut() { + let addresses = previous_ranges + .get(port) + .map_or_else(Default::default, |info| info.addresses.clone()); + range.addresses.resolve_address_groups(&addresses); + } + Ok(()) + })?; self.derive_addresses(mdns, gateways, available_ports) } @@ -997,7 +1007,7 @@ mod tests { }; use crate::hostname::ServerHostname; use crate::net::forward::AvailablePorts; - use crate::net::host::binding::BindOptions; + use crate::net::host::binding::{BindOptions, DerivedAddressInfo}; use crate::net::service_interface::HostnameMetadata; use crate::prelude::*; @@ -1491,4 +1501,298 @@ mod tests { ); } } + + const DOMAIN: &str = "smp.example.com"; + + fn exported_host(ports: &mut AvailablePorts, port: u16) -> Model { + use crate::net::service_interface::{AddressInfo, ServiceInterface, ServiceInterfaceType}; + + let mut host = host(); + host.add_binding(ports, port, plain(port), false).unwrap(); + host.as_bindings_mut() + .mutate(|b| { + let id: crate::ServiceInterfaceId = "ui".parse().unwrap(); + b.get_mut(&port).unwrap().interfaces.insert( + id.clone(), + ServiceInterface { + id, + name: "ui".into(), + description: String::new(), + masked: false, + address_info: AddressInfo { + username: None, + host_id: "host".parse().unwrap(), + internal_port: port, + scheme: Some(InternedString::intern("http")), + ssl_scheme: None, + suffix: String::new(), + }, + interface_type: ServiceInterfaceType::Ui, + preferred_launcher_address: None, + }, + ); + Ok(()) + }) + .unwrap(); + host + } + + fn add_public_domain(host: &mut Model) { + host.as_public_domains_mut() + .insert( + &InternedString::intern(DOMAIN), + &PublicDomainConfig { + gateway: gw("wg-in"), + acme: None, + }, + ) + .unwrap(); + } + + fn converge( + host: &mut Model, + gateways: &OrdMap, + ports: &AvailablePorts, + ) { + host.update_addresses( + &ServerHostname::new(InternedString::intern("server")).unwrap(), + gateways, + ports, + ) + .unwrap(); + } + + fn reconnect( + host: &mut Model, + gateways: &mut OrdMap, + ports: &AvailablePorts, + change: impl FnOnce(&mut NetworkInterfaceInfo), + ) { + let mut info = gateways[&gw("wg-in")].clone(); + change(&mut info); + gateways.insert(gw("wg-in"), info); + converge(host, gateways, ports); + } + + fn set_wan_ip(info: &mut NetworkInterfaceInfo, wan_ip: Option) { + Arc::make_mut(info.ip_info.as_mut().unwrap()).wan_ip = wan_ip; + } + + fn on(addresses: &DerivedAddressInfo) -> Vec { + addresses + .enabled() + .into_iter() + .filter(|a| a.public) + .map(|a| match a.to_socket_addr() { + Some(sa) => sa.to_string(), + None => a.hostname.to_string(), + }) + .collect() + } + + fn binding_on(host: &Model, port: u16) -> Vec { + on(&host.de().unwrap().bindings[&port].addresses) + } + + fn forward_srcs(host: &Model) -> Vec { + host.de() + .unwrap() + .port_forwards + .iter() + .map(|f| f.src.to_string()) + .collect() + } + + /// The operator's switch on the plain public domain, which groups its gateway's public IPs. + fn switch_domain(addresses: &mut DerivedAddressInfo, port: u16, enabled: bool) { + let address = addresses + .available + .iter() + .find(|a| &*a.hostname == DOMAIN && a.port == Some(port)) + .unwrap() + .clone(); + crate::net::host::binding::set_address_enabled_with_consent( + addresses, &address, enabled, false, + ) + .unwrap(); + } + + fn switch_binding_domain(host: &mut Model, port: u16, enabled: bool) { + host.as_bindings_mut() + .mutate(|b| { + switch_domain(&mut b.get_mut(&port).unwrap().addresses, port, enabled); + Ok(()) + }) + .unwrap(); + } + + fn single_gateway() -> OrdMap { + [(gw("wg-in"), wireguard(GatewayType::InboundOutbound))] + .into_iter() + .collect() + } + + #[test] + fn an_enabled_plain_domain_keeps_its_wan_ip_on_through_a_new_lease() { + let mut gateways = single_gateway(); + let mut ports = AvailablePorts::new(); + let mut host = exported_host(&mut ports, 5223); + add_public_domain(&mut host); + converge(&mut host, &gateways, &ports); + switch_binding_domain(&mut host, 5223, true); + converge(&mut host, &gateways, &ports); + assert_eq!(binding_on(&host, 5223), ["198.51.100.2:5223", DOMAIN]); + + reconnect(&mut host, &mut gateways, &ports, |info| { + set_wan_ip(info, Some(Ipv4Addr::new(203, 0, 113, 9))) + }); + + assert_eq!(binding_on(&host, 5223), ["203.0.113.9:5223", DOMAIN]); + assert_eq!(forward_srcs(&host), ["203.0.113.9:5223"]); + } + + #[test] + fn an_enabled_plain_domain_keeps_its_wan_ip_on_through_a_lan_first_reconnect() { + let mut gateways = single_gateway(); + let mut ports = AvailablePorts::new(); + let mut host = exported_host(&mut ports, 5223); + add_public_domain(&mut host); + converge(&mut host, &gateways, &ports); + switch_binding_domain(&mut host, 5223, true); + converge(&mut host, &gateways, &ports); + + reconnect(&mut host, &mut gateways, &ports, |info| info.ip_info = None); + assert_eq!(binding_on(&host, 5223), [DOMAIN]); + reconnect(&mut host, &mut gateways, &ports, |info| { + *info = wireguard(GatewayType::InboundOutbound); + set_wan_ip(info, None); + }); + assert_eq!(binding_on(&host, 5223), [DOMAIN]); + reconnect(&mut host, &mut gateways, &ports, |info| { + set_wan_ip(info, Some(Ipv4Addr::new(203, 0, 113, 9))) + }); + + assert_eq!(binding_on(&host, 5223), ["203.0.113.9:5223", DOMAIN]); + assert_eq!(forward_srcs(&host), ["203.0.113.9:5223"]); + } + + #[test] + fn a_disabled_plain_domain_leaves_the_new_wan_ip_off() { + let mut gateways = single_gateway(); + let mut ports = AvailablePorts::new(); + let mut host = exported_host(&mut ports, 5223); + add_public_domain(&mut host); + converge(&mut host, &gateways, &ports); + switch_binding_domain(&mut host, 5223, true); + converge(&mut host, &gateways, &ports); + switch_binding_domain(&mut host, 5223, false); + converge(&mut host, &gateways, &ports); + + reconnect(&mut host, &mut gateways, &ports, |info| { + set_wan_ip(info, Some(Ipv4Addr::new(203, 0, 113, 9))) + }); + + assert!(binding_on(&host, 5223).is_empty()); + assert!(forward_srcs(&host).is_empty()); + } + + #[test] + fn a_bare_wan_ip_opt_in_does_not_follow_a_new_lease() { + let mut gateways = single_gateway(); + let mut ports = AvailablePorts::new(); + let mut host = exported_host(&mut ports, 9735); + converge(&mut host, &gateways, &ports); + host.as_bindings_mut() + .mutate(|b| { + let addresses = &mut b.get_mut(&9735).unwrap().addresses; + addresses + .enabled + .insert("198.51.100.2:9735".parse().unwrap()); + Ok(()) + }) + .unwrap(); + converge(&mut host, &gateways, &ports); + assert_eq!(forward_srcs(&host), ["198.51.100.2:9735"]); + + reconnect(&mut host, &mut gateways, &ports, |info| { + set_wan_ip(info, Some(Ipv4Addr::new(203, 0, 113, 9))) + }); + + assert!(binding_on(&host, 9735).is_empty()); + assert!(forward_srcs(&host).is_empty()); + } + + #[test] + fn an_enabled_plain_domain_keeps_its_range_wan_ip_on_through_a_link_drop() { + let mut gateways = single_gateway(); + let mut ports = AvailablePorts::new(); + let mut host = host(); + add_public_domain(&mut host); + host.add_binding_range(&mut ports, 28332, 40000, 4, false, Default::default()) + .unwrap(); + converge(&mut host, &gateways, &ports); + host.as_binding_ranges_mut() + .mutate(|r| { + switch_domain(&mut r.get_mut(&28332).unwrap().addresses, 40000, true); + Ok(()) + }) + .unwrap(); + converge(&mut host, &gateways, &ports); + let range_on = + |host: &Model| on(&host.de().unwrap().binding_ranges[&28332].addresses); + assert_eq!(range_on(&host), ["198.51.100.2:40000", DOMAIN]); + + reconnect(&mut host, &mut gateways, &ports, |info| info.ip_info = None); + reconnect(&mut host, &mut gateways, &ports, |info| { + *info = wireguard(GatewayType::InboundOutbound); + set_wan_ip(info, None); + }); + reconnect(&mut host, &mut gateways, &ports, |info| { + set_wan_ip(info, Some(Ipv4Addr::new(203, 0, 113, 9))) + }); + + assert_eq!(range_on(&host), ["203.0.113.9:40000", DOMAIN]); + } + + fn dual_stack(guas: &[&str]) -> NetworkInterfaceInfo { + let mut info = wireguard(GatewayType::InboundOutbound); + let ip_info = Arc::make_mut(info.ip_info.as_mut().unwrap()); + ip_info.subnets = ["192.0.2.2/24"] + .iter() + .chain(guas) + .map(|s| s.parse::().unwrap()) + .collect(); + info + } + + #[test] + fn an_enabled_plain_domain_keeps_its_gua_public_through_a_prefix_move() { + let mut gateways: OrdMap = + [(gw("wg-in"), dual_stack(&["2001:db8:1::5/64"]))] + .into_iter() + .collect(); + let mut ports = AvailablePorts::new(); + let mut host = exported_host(&mut ports, 5223); + add_public_domain(&mut host); + converge(&mut host, &gateways, &ports); + switch_binding_domain(&mut host, 5223, true); + converge(&mut host, &gateways, &ports); + assert_eq!( + binding_on(&host, 5223), + ["198.51.100.2:5223", "[2001:db8:1::5]:5223", DOMAIN] + ); + + reconnect(&mut host, &mut gateways, &ports, |info| info.ip_info = None); + reconnect(&mut host, &mut gateways, &ports, |info| { + *info = dual_stack(&[]); + }); + reconnect(&mut host, &mut gateways, &ports, |info| { + *info = dual_stack(&["2001:db8:2::5/64"]); + }); + + assert_eq!( + binding_on(&host, 5223), + ["198.51.100.2:5223", "[2001:db8:2::5]:5223", DOMAIN] + ); + } } diff --git a/shared-libs/crates/start-core/src/version/mod.rs b/shared-libs/crates/start-core/src/version/mod.rs index 741088b8c1..d6d5d1394d 100644 --- a/shared-libs/crates/start-core/src/version/mod.rs +++ b/shared-libs/crates/start-core/src/version/mod.rs @@ -907,7 +907,7 @@ mod tests { ("0.4.1.3", "0.4.2", 0), ("0.4.2", "0.4.2.1", 2), ("0.4.2.1", "0.4.2.2", 0), - ("0.4.2.2", "0.4.3", 0), + ("0.4.2.2", "0.4.3", 1), ] { let previous = from_value::(json!(from)) .unwrap() @@ -1038,7 +1038,10 @@ mod tests { db["public"]["serverInfo"]["version"], to_value(¤t.semver()).unwrap() ); - assert_eq!(applied_migration_revision(&mut db).unwrap(), 0); + assert_eq!( + applied_migration_revision(&mut db).unwrap(), + current.migration_revision() + ); } } diff --git a/shared-libs/crates/start-core/src/version/v0_4_3.rs b/shared-libs/crates/start-core/src/version/v0_4_3.rs index e3ffc6e595..0e8c1a4f5e 100644 --- a/shared-libs/crates/start-core/src/version/v0_4_3.rs +++ b/shared-libs/crates/start-core/src/version/v0_4_3.rs @@ -1,7 +1,10 @@ use exver::VersionRange; use super::v0_3_5::V0_3_0_COMPAT; +use super::v0_4_0_2::for_each_host; use super::{VersionT, v0_4_2_2}; +use crate::net::host::binding::{DerivedAddressInfo, set_nonssl_wan_group}; +use crate::net::service_interface::HostnameMetadata; use crate::prelude::*; lazy_static::lazy_static! { @@ -21,13 +24,134 @@ impl VersionT for Version { fn semver(self) -> exver::Version { V0_4_3.clone() } + fn migration_revision(self) -> usize { + 1 + } fn compat(self) -> &'static VersionRange { &V0_3_0_COMPAT } - fn up(self, _db: &mut Value, _: Self::PreUpRes) -> Result { + fn up(self, db: &mut Value, _: Self::PreUpRes) -> Result { + for_each_host(db, |host| { + let Some(ranges) = host.get_mut("bindingRanges").and_then(Value::as_object_mut) else { + return; + }; + for (_, range) in ranges.iter_mut() { + if let Some(addresses) = range.get_mut("addresses") { + group_enabled_plain_domains(addresses); + } + } + }); Ok(Value::Null) } fn down(self, _db: &mut Value) -> Result<(), Error> { Ok(()) } } + +/// Switches on the public IPs grouped with each enabled plain public domain of a range. +/// The domain's forward already exposes them; earlier versions left them off after a renumber. +fn group_enabled_plain_domains(addresses: &mut Value) { + let Ok(mut info) = from_value::(addresses.clone()) else { + return; + }; + let groups: Vec<_> = info + .enabled() + .into_iter() + .filter(|a| !a.ssl) + .filter_map(|a| match (&a.metadata, a.port) { + (HostnameMetadata::PublicDomain { gateway }, Some(port)) => { + Some((gateway.clone(), port)) + } + _ => None, + }) + .collect(); + if groups.is_empty() { + return; + } + for (gateway, port) in groups { + set_nonssl_wan_group(&mut info, &gateway, port, true); + } + if let Ok(value) = to_value(&info) { + *addresses = value; + } +} + +#[cfg(test)] +mod tests { + use imbl_value::json; + + use super::*; + + fn row(hostname: &str, public: bool, metadata: Value) -> Value { + json!({ + "ssl": false, + "public": public, + "hostname": hostname, + "port": 40000, + "metadata": metadata, + }) + } + + fn migrated(addresses: Value) -> Value { + let mut db = json!({ + "public": { + "serverInfo": { "network": { "host": { "bindings": {} } } }, + "packageData": { "service": { "hosts": { "p2p": { + "bindings": {}, + "bindingRanges": { "28332": { "addresses": addresses } } + } } } } + } + }); + Version.up(&mut db, ()).unwrap(); + db["public"]["packageData"]["service"]["hosts"]["p2p"]["bindingRanges"]["28332"] + ["addresses"] + .clone() + } + + fn range_on(addresses: Value) -> Vec { + let info: DerivedAddressInfo = from_value(addresses).unwrap(); + info.enabled() + .into_iter() + .filter(|a| a.public) + .map(|a| match a.to_socket_addr() { + Some(sa) => sa.to_string(), + None => a.hostname.to_string(), + }) + .collect() + } + + fn renumbered(domain_disabled: bool) -> Value { + let disabled = if domain_disabled { + json!([["smp.example.com", 40000]]) + } else { + json!([]) + }; + json!({ + "enabled": ["198.51.100.2:40000"], + "disabled": disabled, + "available": [ + row("203.0.113.9", true, json!({ "kind": "ipv4", "gateway": "wg-in" })), + row( + "smp.example.com", + true, + json!({ "kind": "public-domain", "gateway": "wg-in" }), + ), + ], + }) + } + + #[test] + fn a_renumbered_range_keeps_its_enabled_plain_domain_and_turns_its_ip_on() { + let addresses = migrated(renumbered(false)); + assert_eq!( + range_on(addresses.clone()), + ["203.0.113.9:40000", "smp.example.com"] + ); + assert_eq!(migrated(addresses.clone()), addresses); + } + + #[test] + fn a_range_whose_plain_domain_is_off_keeps_its_ip_off() { + assert!(range_on(migrated(renumbered(true))).is_empty()); + } +} diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/effects.schemas.ts b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/effects.schemas.ts index 8d63856935..c1d16a3623 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/effects.schemas.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/effects.schemas.ts @@ -2771,6 +2771,8 @@ export const DepInfo: z.ZodIntersection< export const DerivedAddressInfo: z.ZodObject<{ /** * User override: enable these addresses (only for public IP & port) + * An opt-in names one literal address and lapses when the gateway renumbers. + * Only an enabled plain public domain carries its group's public IPs across. */ enabled: z.ZodArray /** @@ -2827,10 +2829,12 @@ export const DerivedAddressInfo: z.ZodObject<{ }> = /* @__PURE__ */ object({ /** * User override: enable these addresses (only for public IP & port) + * An opt-in names one literal address and lapses when the gateway renumbers. + * Only an enabled plain public domain carries its group's public IPs across. */ enabled: z.array(z.string()).meta({ description: - 'User override: enable these addresses (only for public IP & port)', + "User override: enable these addresses (only for public IP & port)\nAn opt-in names one literal address and lapses when the gateway renumbers.\nOnly an enabled plain public domain carries its group's public IPs across.", }), /** * User override: disable these addresses (only for domains and private IP & port) diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.schemas.ts b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.schemas.ts index 959346efe8..1ea3df0ff9 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.schemas.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/rpc/start-os.schemas.ts @@ -5892,6 +5892,8 @@ export const BindingSetGuaWanParams: z.ZodObject<{ export const DerivedAddressInfo: z.ZodObject<{ /** * User override: enable these addresses (only for public IP & port) + * An opt-in names one literal address and lapses when the gateway renumbers. + * Only an enabled plain public domain carries its group's public IPs across. */ enabled: z.ZodArray /** @@ -5948,10 +5950,12 @@ export const DerivedAddressInfo: z.ZodObject<{ }> = /* @__PURE__ */ object({ /** * User override: enable these addresses (only for public IP & port) + * An opt-in names one literal address and lapses when the gateway renumbers. + * Only an enabled plain public domain carries its group's public IPs across. */ enabled: z.array(z.string()).meta({ description: - 'User override: enable these addresses (only for public IP & port)', + "User override: enable these addresses (only for public IP & port)\nAn opt-in names one literal address and lapses when the gateway renumbers.\nOnly an enabled plain public domain carries its group's public IPs across.", }), /** * User override: disable these addresses (only for domains and private IP & port) diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts b/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts index 97f5bb262c..0df25a9ea1 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts @@ -6657,6 +6657,8 @@ export const DepInfo: z.ZodIntersection< export const DerivedAddressInfo: z.ZodObject<{ /** * User override: enable these addresses (only for public IP & port) + * An opt-in names one literal address and lapses when the gateway renumbers. + * Only an enabled plain public domain carries its group's public IPs across. */ enabled: z.ZodArray /** @@ -6713,10 +6715,12 @@ export const DerivedAddressInfo: z.ZodObject<{ }> = /* @__PURE__ */ object({ /** * User override: enable these addresses (only for public IP & port) + * An opt-in names one literal address and lapses when the gateway renumbers. + * Only an enabled plain public domain carries its group's public IPs across. */ enabled: z.array(z.string()).meta({ description: - 'User override: enable these addresses (only for public IP & port)', + "User override: enable these addresses (only for public IP & port)\nAn opt-in names one literal address and lapses when the gateway renumbers.\nOnly an enabled plain public domain carries its group's public IPs across.", }), /** * User override: disable these addresses (only for domains and private IP & port) From f6491f8574cc08cfe01e7aefbc01a2bded163e81 Mon Sep 17 00:00:00 2001 From: gStart9 <106188942+gStart9@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:52:28 +0000 Subject: [PATCH 36/38] fix(start-os): update re-added SSH keys in place and publish them to patch-db (#4757) * fix(start-os): refuse to add an SSH key that is already authorized StartOS stores SSH keys by MD5 fingerprint, so adding a key that was already authorized silently replaced the stored entry. The UI then listed the returned key a second time, and removing either row deleted the single stored entry, so both rows disappeared. ssh.add now refuses a key whose fingerprint is already stored with a Duplicate error that carries the existing key's details as its info. The SSH page catches that error and opens a dialog naming the existing key by hostname, algorithm, fingerprint and creation date. Co-Authored-By: Claude Opus 5.5 * fix(start-os): update re-added SSH keys in place and publish them to patch-db Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(start-os): valid SSH test key, 0.4.3 revision expectation, single authorized_keys writer Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * chore: regenerate TS bindings for public sshPubkeys Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * style: format SSH key changes Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * test: include public sshPubkeys in full database fixtures Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(start-os): bump updated_at when an SSH key is re-added Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(start-os): bump 0.4.3 migration revision to 2 for the SSH key move Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(start-os): rebind local apt archives when retrying lb chroot Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(start-os): render SSH keys straight from patch-db Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * fix(start-os): parse SSH key options and wait for the cached sshPubkeys collection Helix-Harness: claude-code Helix-Model: claude-opus-5-5 * style: format SSH key UI changes Helix-Harness: claude-code Helix-Model: claude-opus-5-5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: helix-white <267227783+helix-a@users.noreply.github.com> Co-authored-by: helix-red <355572797+helix-red@users.noreply.github.com> --- projects/start-os/build/image-recipe/build.sh | 8 +- .../start-os/build/tests/dns-config-test.sh | 2 +- .../patch-fixed-duplicate-ssh-key.md | 5 + .../start-os/web/ui/scripts/ssh-keys.test.mjs | 133 ++++++++++++++++++ .../routes/system/routes/ssh/ssh.component.ts | 41 +++--- .../services/api/embassy-mock-api.service.ts | 27 +++- .../web/ui/src/app/services/api/mock-patch.ts | 10 ++ .../src/app/services/patch-db/data-model.ts | 5 +- .../start-os/web/ui/src/app/utils/ssh-keys.ts | 18 +++ .../crates/start-core/src/db/model/mod.rs | 2 - .../crates/start-core/src/db/model/private.rs | 2 - .../crates/start-core/src/db/model/public.rs | 4 + .../crates/start-core/src/db/prelude.rs | 4 +- shared-libs/crates/start-core/src/init.rs | 2 +- .../crates/start-core/src/net/host/address.rs | 1 + .../src/net/host/binding/reassign/tests.rs | 1 + shared-libs/crates/start-core/src/ssh.rs | 127 ++++++++++++----- .../crates/start-core/src/version/mod.rs | 2 +- .../crates/start-core/src/version/v0_4_3.rs | 85 ++++++++++- .../lib/osBindings/types.schemas.ts | 27 ++++ .../start-core/lib/osBindings/types.ts | 10 ++ 21 files changed, 446 insertions(+), 70 deletions(-) create mode 100644 projects/start-os/changelog/patch-fixed-duplicate-ssh-key.md create mode 100644 projects/start-os/web/ui/scripts/ssh-keys.test.mjs create mode 100644 projects/start-os/web/ui/src/app/utils/ssh-keys.ts diff --git a/projects/start-os/build/image-recipe/build.sh b/projects/start-os/build/image-recipe/build.sh index 87a27cbce5..49f7b9a38c 100755 --- a/projects/start-os/build/image-recipe/build.sh +++ b/projects/start-os/build/image-recipe/build.sh @@ -430,7 +430,13 @@ else cat ./chroot/debootstrap/debootstrap.log exit $EXIT fi -retry lb chroot +# live-build's failure cleanup unmounts the local archives but keeps the +# `chroot_archives` stagefile, which would skip binding them again. +lb_chroot() { + rm -f .build/chroot_archives + lb chroot +} +retry lb_chroot "$SOURCE_DIR/kernel-backports/verify-kernel-backports.sh" chroot "$IB_TARGET_ARCH" # riscv64 binaries target RVA23, which the build host may lack. diff --git a/projects/start-os/build/tests/dns-config-test.sh b/projects/start-os/build/tests/dns-config-test.sh index 2d38f52169..97774b49c7 100755 --- a/projects/start-os/build/tests/dns-config-test.sh +++ b/projects/start-os/build/tests/dns-config-test.sh @@ -59,6 +59,6 @@ try { } const recipe = read(base + 'build/image-recipe/build.sh') assert.doesNotMatch(recipe, /resolv\.conf\.bak/, 'must not restore build-host DNS into the shipped rootfs') -assert.match(recipe, /\nretry lb chroot\n[\s\S]*?\nretry lb installer\nretry lb binary_chroot\nretry lb chroot_prep install all mode-apt-install-binary mode-archives-chroot\nretry lb binary_rootfs\n[\s\S]*?if \[ "\$\{IMAGE_TYPE\}" = iso \]; then/, 'ISO and img share live-build resolver cleanup and rootfs assembly') +assert.match(recipe, /\nretry lb_chroot\n[\s\S]*?\nretry lb installer\nretry lb binary_chroot\nretry lb chroot_prep install all mode-apt-install-binary mode-archives-chroot\nretry lb binary_rootfs\n[\s\S]*?if \[ "\$\{IMAGE_TYPE\}" = iso \]; then/, 'ISO and img share live-build resolver cleanup and rootfs assembly') console.log('DNS configuration preserves build DNS until live-build restores the runtime OS stub') NODE diff --git a/projects/start-os/changelog/patch-fixed-duplicate-ssh-key.md b/projects/start-os/changelog/patch-fixed-duplicate-ssh-key.md new file mode 100644 index 0000000000..77bb4596cb --- /dev/null +++ b/projects/start-os/changelog/patch-fixed-duplicate-ssh-key.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Re-adding an SSH key updates its existing entry, keeping its creation date, instead of duplicating its row. The SSH key list stays synchronized across browser sessions and CLI changes. diff --git a/projects/start-os/web/ui/scripts/ssh-keys.test.mjs b/projects/start-os/web/ui/scripts/ssh-keys.test.mjs new file mode 100644 index 0000000000..04477cf0f9 --- /dev/null +++ b/projects/start-os/web/ui/scripts/ssh-keys.test.mjs @@ -0,0 +1,133 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import '@angular/compiler' +import { createEnvironmentInjector, runInInjectionContext } from '@angular/core' +import { Subject } from 'rxjs' +import { loadTypeScript } from './typescript-loader.mjs' + +loadTypeScript( + new Map([ + [ + '@start9labs/shared', + `export class DialogService {} + export class DocsLinkDirective {} + export class i18nPipe {} + export class TaskService {}`, + ], + ['@start9labs/start-core', 'export const ISB = {}'], + ['@taiga-ui/core', 'export class TuiButton {}'], + ['src/app/services/api/embassy-api.service', 'export class ApiService {}'], + [ + 'src/app/services/form-dialog.service', + 'export class FormDialogService {}', + ], + ['src/app/services/title.service', 'export class TitleDirective {}'], + [ + 'src/app/routes/portal/components/form.component', + 'export class FormComponent {}', + ], + [ + 'src/app/utils/configBuilderToSpec', + 'export const configBuilderToSpec = value => value', + ], + ['./table.component', 'export class SSHTableComponent {}'], + ]), +) +const { PatchDB } = await import('patch-db-client') +const { DialogService, i18nPipe, TaskService } = + await import('@start9labs/shared') +const { ApiService } = await import('src/app/services/api/embassy-api.service') +const { FormDialogService } = + await import('src/app/services/form-dialog.service') +const { sshKeyRows } = await import('src/app/utils/ssh-keys') +const { default: Ssh } = + await import('src/app/routes/portal/routes/system/routes/ssh/ssh.component') + +const keyData = + 'AAAAC3NzaC1lZDI1NTE5AAAAIMcFf+jmv4w+tRbA1aXDvovqViM0NVRu86Hk5kcQItfI' +const fingerprint = '00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff' +const createdAt = '2020-01-01T00:00:00Z' +const stored = value => ({ + created_at: createdAt, + updated_at: '2021-01-01T00:00:00Z', + value, +}) +const expected = hostname => ({ + fingerprint, + alg: 'ssh-ed25519', + hostname, + createdAt, +}) + +for (const [name, options] of [ + ['bare key', ''], + ['restricted key', 'restrict '], + ['multiple options', 'from="192.0.2.0/24",no-pty '], + ['quoted command', 'command="echo ssh-ed25519 AAAA decoy",no-pty '], + [ + 'escaped quotes', + String.raw`command="printf \"ssh-rsa AAAA decoy\"",restrict `, + ], +]) { + test(`${name} keeps options out of the algorithm and hostname`, () => { + const hostname = 'workstation rack\tone' + assert.deepEqual( + sshKeyRows({ + [fingerprint]: stored(`${options}ssh-ed25519 ${keyData} ${hostname}`), + }), + [expected(hostname)], + ) + }) +} + +test('empty collections and keys without comments remain displayable', () => { + assert.deepEqual(sshKeyRows({}), []) + for (const suffix of ['', ' ']) { + assert.deepEqual( + sshKeyRows({ + [fingerprint]: stored(`ssh-ed25519 ${keyData}${suffix}`), + }), + [expected('')], + ) + } +}) + +test('an older cached snapshot stays loading until the SSH collection arrives', t => { + const updates = new Subject() + const patch = new PatchDB(updates) + patch.start() + updates.next([{ id: 7, value: { serverInfo: {} } }]) + const injector = createEnvironmentInjector([ + { provide: PatchDB, useValue: patch }, + ...[ + ApiService, + TaskService, + FormDialogService, + i18nPipe, + DialogService, + ].map(provide => ({ provide, useValue: {} })), + ]) + t.after(() => { + injector.destroy() + patch.stop() + }) + const page = runInInjectionContext(injector, () => new Ssh()) + assert.equal(page.keys(), null) + + updates.next([ + { + id: 8, + value: { + serverInfo: {}, + sshPubkeys: { + [fingerprint]: stored(`restrict ssh-ed25519 ${keyData} workstation`), + }, + }, + }, + ]) + assert.deepEqual(page.keys(), [expected('workstation')]) + updates.next([ + { id: 9, patch: [{ op: 'remove', path: `/sshPubkeys/${fingerprint}` }] }, + ]) + assert.deepEqual(page.keys(), []) +}) diff --git a/projects/start-os/web/ui/src/app/routes/portal/routes/system/routes/ssh/ssh.component.ts b/projects/start-os/web/ui/src/app/routes/portal/routes/system/routes/ssh/ssh.component.ts index e25384121a..6a1fff567f 100644 --- a/projects/start-os/web/ui/src/app/routes/portal/routes/system/routes/ssh/ssh.component.ts +++ b/projects/start-os/web/ui/src/app/routes/portal/routes/system/routes/ssh/ssh.component.ts @@ -1,5 +1,6 @@ import { CommonModule } from '@angular/common' import { Component, inject, viewChild } from '@angular/core' +import { toSignal } from '@angular/core/rxjs-interop' import { RouterLink } from '@angular/router' import { DialogService, @@ -9,12 +10,15 @@ import { } from '@start9labs/shared' import { ISB, T } from '@start9labs/start-core' import { TuiButton } from '@taiga-ui/core' -import { filter, from, merge, Subject } from 'rxjs' +import { PatchDB } from 'patch-db-client' +import { filter, map } from 'rxjs' import { FormComponent } from 'src/app/routes/portal/components/form.component' import { ApiService } from 'src/app/services/api/embassy-api.service' import { FormDialogService } from 'src/app/services/form-dialog.service' +import { DataModel } from 'src/app/services/patch-db/data-model' import { TitleDirective } from 'src/app/services/title.service' import { configBuilderToSpec } from 'src/app/utils/configBuilderToSpec' +import { sshKeyRows } from 'src/app/utils/ssh-keys' import { SSHTableComponent } from './table.component' @Component({ @@ -35,7 +39,7 @@ import { SSHTableComponent } from './table.component' >
- @let keys = keys$ | async; + @let keys = this.keys();
{{ 'SSH Access' | i18n }} @@ -55,7 +59,7 @@ import { SSHTableComponent } from './table.component' class="delete" size="xs" appearance="primary-destructive" - (click)="remove(keys || [])" + (click)="remove()" > {{ 'Remove' | i18n }} @@ -65,13 +69,13 @@ import { SSHTableComponent } from './table.component' size="xs" iconStart="@tui.plus" [style.margin]="'0 0.5rem 0 auto'" - (click)="add(keys || [])" + (click)="add()" > {{ 'Add' | i18n }} }
-
+
`, styles: ` @@ -100,13 +104,18 @@ export default class SystemSSHComponent { private readonly i18n = inject(i18nPipe) private readonly dialogs = inject(DialogService) - private readonly local$ = new Subject() + protected readonly keys = toSignal( + inject>(PatchDB).watch$('sshPubkeys').pipe( + // Cached snapshots can predate `sshPubkeys`. + filter(Boolean), + map(sshKeyRows), + ), + { initialValue: null }, + ) + protected readonly tableKeys = + viewChild>('table') - readonly keys$ = merge(from(this.api.rpc.ssh.list({})), this.local$) - - protected tableKeys = viewChild>('table') - - async add(all: readonly T.SshKeyResponse[]) { + async add() { const spec = ISB.InputSpec.of({ key: ISB.Value.text({ name: this.i18n.transform('Public Key'), @@ -131,8 +140,7 @@ export default class SystemSSHComponent { text: this.i18n.transform('Save'), handler: async ({ key }: typeof spec._TYPE) => this.tasks.run(async () => { - const newKey = await this.api.rpc.ssh.add({ key }) - this.local$.next([newKey, ...all]) + await this.api.rpc.ssh.add({ key }) }, 'Saving'), }, ], @@ -140,13 +148,13 @@ export default class SystemSSHComponent { }) } - remove(all: readonly T.SshKeyResponse[]) { + remove() { this.dialogs .openConfirm({ label: 'Are you sure?', size: 's' }) .pipe(filter(Boolean)) .subscribe(async () => { const selected = this.tableKeys()?.selected() || [] - const fingerprints = selected.map(s => s.fingerprint) || [] + const fingerprints = selected.map(s => s.fingerprint) this.tasks.run(async () => { await Promise.all( @@ -154,9 +162,6 @@ export default class SystemSSHComponent { this.api.rpc.ssh.remove({ fingerprint }), ), ) - this.local$.next( - all.filter(s => !fingerprints.includes(s.fingerprint)), - ) this.tableKeys()?.selected.set([]) }, 'Removing') }) diff --git a/projects/start-os/web/ui/src/app/services/api/embassy-mock-api.service.ts b/projects/start-os/web/ui/src/app/services/api/embassy-mock-api.service.ts index 34211a0cd5..1605444bf9 100644 --- a/projects/start-os/web/ui/src/app/services/api/embassy-mock-api.service.ts +++ b/projects/start-os/web/ui/src/app/services/api/embassy-mock-api.service.ts @@ -65,6 +65,7 @@ import { toAuthorityUrl } from 'src/app/utils/acme' import { getCurrentManifest, getManifest } from 'src/app/utils/get-package-data' import { getDriveName } from 'src/app/utils/get-drive-name' import { parsePemPublicKey, parsePublicKeys } from 'src/app/utils/public-keys' +import { sshKeyRows } from 'src/app/utils/ssh-keys' import { BackupRun } from 'src/app/routes/portal/routes/system/routes/backups/backup.types' import { Mock } from './api.fixures' import { BTC_ICON, LND_ICON, PROXY_ICON } from './api-icons' @@ -921,16 +922,32 @@ export class MockApiService extends ApiService implements StartupApiService { await pauseFor(2000) return null }, - 'ssh.list': async params => { + 'ssh.list': async () => { await pauseFor(2000) - return Mock.SshKeys + return sshKeyRows(mockPatchData.sshPubkeys) }, - 'ssh.add': async params => { + 'ssh.add': async ({ key }) => { await pauseFor(2000) - return Mock.SshKey + const fingerprint = Mock.SshKey.fingerprint + const existing = mockPatchData.sshPubkeys[fingerprint] + const now = new Date().toISOString() + const stored = { + created_at: existing?.created_at ?? now, + updated_at: now, + value: key, + } + mockPatchData.sshPubkeys[fingerprint] = stored + await this.mockRevision([ + { op: PatchOp.ADD, path: `/sshPubkeys/${fingerprint}`, value: stored }, + ]) + return sshKeyRows({ [fingerprint]: stored })[0]! }, - 'ssh.remove': async params => { + 'ssh.remove': async ({ fingerprint }) => { await pauseFor(2000) + delete mockPatchData.sshPubkeys[fingerprint] + await this.mockRevision([ + { op: PatchOp.REMOVE, path: `/sshPubkeys/${fingerprint}` }, + ]) return null }, 'volumes.create': async ({ name, source }) => { diff --git a/projects/start-os/web/ui/src/app/services/api/mock-patch.ts b/projects/start-os/web/ui/src/app/services/api/mock-patch.ts index 6816e71d34..ff70e1a51d 100644 --- a/projects/start-os/web/ui/src/app/services/api/mock-patch.ts +++ b/projects/start-os/web/ui/src/app/services/api/mock-patch.ts @@ -103,6 +103,16 @@ export function mockOsUpdateCache( } export const mockPatchData: DataModel = { + sshPubkeys: Object.fromEntries( + Mock.SshKeys.map(key => [ + key.fingerprint, + { + created_at: key.createdAt, + updated_at: key.createdAt, + value: `${key.alg} mock ${key.hostname}`, + }, + ]), + ), registryCache: { [defaultRegistries.start9]: mockRegistryCache( defaultRegistries.start9, diff --git a/projects/start-os/web/ui/src/app/services/patch-db/data-model.ts b/projects/start-os/web/ui/src/app/services/patch-db/data-model.ts index 44c8175cba..e3760a45db 100644 --- a/projects/start-os/web/ui/src/app/services/patch-db/data-model.ts +++ b/projects/start-os/web/ui/src/app/services/patch-db/data-model.ts @@ -1,7 +1,10 @@ import { FullKeyboard, Languages } from '@start9labs/shared' import { T } from '@start9labs/start-core' -export type DataModel = Pick & { +export type DataModel = Pick< + T.Public, + 'registryCache' | 'osUpdateCache' | 'sshPubkeys' +> & { ui: UIData serverInfo: T.ServerInfo & { language: Languages diff --git a/projects/start-os/web/ui/src/app/utils/ssh-keys.ts b/projects/start-os/web/ui/src/app/utils/ssh-keys.ts new file mode 100644 index 0000000000..bad136606b --- /dev/null +++ b/projects/start-os/web/ui/src/app/utils/ssh-keys.ts @@ -0,0 +1,18 @@ +import { T } from '@start9labs/start-core' + +// Stored lines retain `authorized_keys` options, including quoted spaces. +export function sshKeyRows(keys: T.SshKeys): T.SshKeyResponse[] { + return Object.entries(keys).map(([fingerprint, key]) => { + const [, alg = '', hostname = ''] = + key.value.match( + /^(?:(?:[^\s"\\]|\\.|"(?:[^"\\]|\\.)*")+\s+)*?((?:sk-)?(?:ssh-|ecdsa-)\S+)\s+[A-Za-z0-9+/]+={0,2}(?:\s(.*))?$/s, + ) ?? [] + + return { + fingerprint, + alg, + hostname, + createdAt: key.created_at, + } + }) +} diff --git a/shared-libs/crates/start-core/src/db/model/mod.rs b/shared-libs/crates/start-core/src/db/model/mod.rs index a23d9b13c9..02d7f195f6 100644 --- a/shared-libs/crates/start-core/src/db/model/mod.rs +++ b/shared-libs/crates/start-core/src/db/model/mod.rs @@ -12,7 +12,6 @@ use crate::net::forward::AvailablePorts; use crate::net::keys::KeyStore; use crate::notifications::Notifications; use crate::prelude::*; -use crate::ssh::SshKeys; use crate::system::KeyboardOptions; use crate::util::serde::{Der64, Pem}; @@ -41,7 +40,6 @@ impl Database { password: account.password.clone(), sessions: Sessions::default(), ssh_privkey: Pem(account.ssh_key.clone()), - ssh_pubkeys: SshKeys::new(), available_ports: AvailablePorts::new(), notifications: Notifications::new(), os_security_notifications: BTreeMap::new(), diff --git a/shared-libs/crates/start-core/src/db/model/private.rs b/shared-libs/crates/start-core/src/db/model/private.rs index ae2c8d97c4..d0da1b5b5c 100644 --- a/shared-libs/crates/start-core/src/db/model/private.rs +++ b/shared-libs/crates/start-core/src/db/model/private.rs @@ -10,7 +10,6 @@ use crate::net::forward::AvailablePorts; use crate::net::keys::KeyStore; use crate::notifications::Notifications; use crate::prelude::*; -use crate::ssh::SshKeys; use crate::update::security::SecurityNotifications; use crate::util::serde::{Der64, Pem}; @@ -26,7 +25,6 @@ pub struct Private { #[serde(default = "generate_server_identity_key", rename = "developerKey")] pub server_identity_key: Der64, pub ssh_privkey: Pem, - pub ssh_pubkeys: SshKeys, pub available_ports: AvailablePorts, pub notifications: Notifications, #[serde(default)] diff --git a/shared-libs/crates/start-core/src/db/model/public.rs b/shared-libs/crates/start-core/src/db/model/public.rs index 09050115e7..1db52c16a3 100644 --- a/shared-libs/crates/start-core/src/db/model/public.rs +++ b/shared-libs/crates/start-core/src/db/model/public.rs @@ -24,6 +24,7 @@ use crate::net::vhost::PassthroughInfo; use crate::nut::NutConfig; use crate::prelude::*; use crate::progress::FullProgress; +use crate::ssh::SshKeys; use crate::system::{KeyboardOptions, SmtpValue}; use crate::trusted_keys::{ Registries, TrustedKeys, initial_os_registry, initial_registries, initial_trusted_keys, @@ -42,6 +43,8 @@ pub struct Public { pub server_info: ServerInfo, pub package_data: AllPackageData, #[serde(default)] + pub ssh_pubkeys: SshKeys, + #[serde(default)] pub registry_cache: BTreeMap, #[serde(default)] pub os_update_cache: Option, @@ -157,6 +160,7 @@ impl Public { keyboard, }, package_data: AllPackageData::default(), + ssh_pubkeys: SshKeys::new(), registry_cache: BTreeMap::new(), os_update_cache: None, disks: Vec::new(), diff --git a/shared-libs/crates/start-core/src/db/prelude.rs b/shared-libs/crates/start-core/src/db/prelude.rs index 70d10c470e..4658d2116e 100644 --- a/shared-libs/crates/start-core/src/db/prelude.rs +++ b/shared-libs/crates/start-core/src/db/prelude.rs @@ -525,12 +525,14 @@ impl<'de, T: DeserializeOwned> Deserialize<'de> for JsonKey { } } -#[derive(Debug, Clone, Deserialize, Serialize)] +#[derive(Debug, Clone, Deserialize, Serialize, VisitFields)] pub struct WithTimeData { pub created_at: DateTime, pub updated_at: DateTime, pub value: T, } +rpc_toolkit::reflect_ts!(impl [T] for WithTimeData where [T: rpc_toolkit::ts::TS]); + impl WithTimeData { pub fn new(value: T) -> Self { let now = Utc::now(); diff --git a/shared-libs/crates/start-core/src/init.rs b/shared-libs/crates/start-core/src/init.rs index fc5882fc6b..8d03e3ce98 100644 --- a/shared-libs/crates/start-core/src/init.rs +++ b/shared-libs/crates/start-core/src/init.rs @@ -242,7 +242,7 @@ pub async fn init( crate::ssh::sync_keys( &hostname, &peek.as_private().as_ssh_privkey().de()?, - &peek.as_private().as_ssh_pubkeys().de()?, + &peek.as_public().as_ssh_pubkeys().de()?, SSH_DIR, ) .await?; diff --git a/shared-libs/crates/start-core/src/net/host/address.rs b/shared-libs/crates/start-core/src/net/host/address.rs index 5f3be31247..a14f1c4100 100644 --- a/shared-libs/crates/start-core/src/net/host/address.rs +++ b/shared-libs/crates/start-core/src/net/host/address.rs @@ -807,6 +807,7 @@ mod test { "disks": [], "sharedVolumes": {}, "backupTargets": {}, + "sshPubkeys": {}, "serverInfo": { "hostname": "server", "network": { diff --git a/shared-libs/crates/start-core/src/net/host/binding/reassign/tests.rs b/shared-libs/crates/start-core/src/net/host/binding/reassign/tests.rs index 21c512bec3..70539552bc 100644 --- a/shared-libs/crates/start-core/src/net/host/binding/reassign/tests.rs +++ b/shared-libs/crates/start-core/src/net/host/binding/reassign/tests.rs @@ -77,6 +77,7 @@ fn database(host: Host, server: Host, ports: AvailablePorts) -> DatabaseModel { "disks": [], "sharedVolumes": {}, "backupTargets": {}, + "sshPubkeys": {}, "serverInfo": { "hostname": "server", "network": { diff --git a/shared-libs/crates/start-core/src/ssh.rs b/shared-libs/crates/start-core/src/ssh.rs index 0c26653b21..4693cbe729 100644 --- a/shared-libs/crates/start-core/src/ssh.rs +++ b/shared-libs/crates/start-core/src/ssh.rs @@ -19,14 +19,34 @@ use crate::util::{FromStrParser, Invoke}; pub const SSH_DIR: &str = "/home/start9/.ssh"; -#[derive(Clone, Debug, Default, Deserialize, Serialize)] +/// Authorized-key intent shared by SSH mutations and subscribed clients. +#[derive(Clone, Debug, Default, Deserialize, Serialize, VisitFields)] pub struct SshKeys(BTreeMap>); + +rpc_toolkit::reflect_ts!(SshKeys); impl SshKeys { pub fn new() -> Self { Self(BTreeMap::new()) } } +impl Model { + /// Reauthorizing a fingerprint replaces its key and keeps its `created_at`. + fn authorize(&mut self, key: SshPubKey) -> Result { + let fingerprint = InternedString::intern(key.0.fingerprint_md5()); + let key = match self.as_idx(&fingerprint) { + Some(existing) => { + let mut existing = existing.de()?; + *existing = key; + existing + } + None => WithTimeData::new(key), + }; + self.insert(&fingerprint, &key)?; + Ok(SshKeyResponse::new(fingerprint, &key)) + } +} + impl From>> for SshKeys { fn from(map: BTreeMap>) -> Self { Self(map) @@ -70,6 +90,16 @@ pub struct SshKeyResponse { rpc_toolkit::reflect_ts!(SshKeyResponse); rpc_toolkit::ts_export!(SshKeyResponse, namespaces = [""]); +impl SshKeyResponse { + fn new(fingerprint: InternedString, key: &WithTimeData) -> Self { + Self { + alg: key.0.keytype().to_owned(), + fingerprint, + hostname: key.0.comment.clone().unwrap_or_default(), + created_at: key.created_at.to_rfc3339(), + } + } +} impl std::fmt::Display for SshKeyResponse { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( @@ -89,7 +119,6 @@ impl std::str::FromStr for SshPubKey { } } -// #[command(subcommands(add, delete, list,))] pub fn ssh() -> ParentHandler { ParentHandler::new() .subcommand( @@ -135,24 +164,12 @@ pub async fn add( ctx: RpcContext, SshAddParams { key }: SshAddParams, ) -> Result { - let mut key = WithTimeData::new(key); - let fingerprint = InternedString::intern(key.0.fingerprint_md5()); let (keys, res) = ctx .db .mutate(move |m| { - m.as_private_mut() - .as_ssh_pubkeys_mut() - .insert(&fingerprint, &key)?; - - Ok(( - m.as_private().as_ssh_pubkeys().de()?, - SshKeyResponse { - alg: key.0.keytype().to_owned(), - fingerprint, - hostname: key.0.comment.take().unwrap_or_default(), - created_at: key.created_at.to_rfc3339(), - }, - )) + let keys = m.as_public_mut().as_ssh_pubkeys_mut(); + let res = keys.authorize(key)?; + Ok((keys.de()?, res)) }) .await .result?; @@ -180,7 +197,7 @@ pub async fn remove( let keys = ctx .db .mutate(|m| { - let keys_ref = m.as_private_mut().as_ssh_pubkeys_mut(); + let keys_ref = m.as_public_mut().as_ssh_pubkeys_mut(); if keys_ref.remove(&fingerprint)?.is_some() { keys_ref.de() } else { @@ -231,19 +248,11 @@ pub async fn list(ctx: RpcContext) -> Result, Error> { ctx.db .peek() .await - .into_private() + .into_public() .into_ssh_pubkeys() .into_entries()? .into_iter() - .map(|(fingerprint, key)| { - let mut key = key.de()?; - Ok(SshKeyResponse { - alg: key.0.keytype().to_owned(), - fingerprint, - hostname: key.0.comment.take().unwrap_or_default(), - created_at: key.created_at.to_rfc3339(), - }) - }) + .map(|(fingerprint, key)| Ok(SshKeyResponse::new(fingerprint, &key.de()?))) .collect() } @@ -302,11 +311,7 @@ pub async fn sync_keys>( f.write_all(b"\n").await?; f.sync_all().await?; - let mut f = create_file(ssh_dir.join("authorized_keys")).await?; - for key in pubkeys.0.values() { - f.write_all(key.0.to_key_format().as_bytes()).await?; - f.write_all(b"\n").await?; - } + sync_pubkeys(pubkeys, ssh_dir).await?; Command::new("chown") .arg("-R") @@ -335,3 +340,59 @@ pub async fn sync_pubkeys>(pubkeys: &SshKeys, ssh_dir: P) -> Resu Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + const KEY: &str = + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMcFf+jmv4w+tRbA1aXDvovqViM0NVRu86Hk5kcQItfI laptop"; + + #[test] + fn reauthorization_updates_the_comment_and_updated_at_but_not_created_at() { + let key: SshPubKey = KEY.parse().unwrap(); + let fingerprint = InternedString::intern(key.0.fingerprint_md5()); + let original = WithTimeData { + value: key, + created_at: "2020-01-01T00:00:00Z".parse().unwrap(), + updated_at: "2021-01-01T00:00:00Z".parse().unwrap(), + }; + let mut keys = Model::new(&SshKeys::from(BTreeMap::from([( + fingerprint.clone(), + original.clone(), + )]))) + .unwrap(); + let response = keys + .authorize(KEY.replace("laptop", "desktop").parse().unwrap()) + .unwrap(); + let saved = keys.as_idx(&fingerprint).unwrap().de().unwrap(); + assert_eq!(keys.de().unwrap().0.len(), 1); + assert_eq!(response.fingerprint, fingerprint); + assert_eq!(response.hostname, "desktop"); + assert_eq!(response.created_at, original.created_at.to_rfc3339()); + assert_eq!(saved.created_at, original.created_at); + assert!(saved.updated_at > original.updated_at); + assert_eq!(saved.0.comment.as_deref(), Some("desktop")); + } + + #[tokio::test] + async fn reauthorizing_after_a_failed_sync_can_repair_authorized_keys() { + let mut keys = Model::new(&SshKeys::new()).unwrap(); + let first = keys.authorize(KEY.parse().unwrap()).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let ssh_dir = dir.path().join("ssh"); + tokio::fs::write(&ssh_dir, "not a directory").await.unwrap(); + assert!(sync_pubkeys(&keys.de().unwrap(), &ssh_dir).await.is_err()); + tokio::fs::remove_file(&ssh_dir).await.unwrap(); + let retry = keys.authorize(KEY.parse().unwrap()).unwrap(); + sync_pubkeys(&keys.de().unwrap(), &ssh_dir).await.unwrap(); + assert_eq!(first.created_at, retry.created_at); + assert_eq!(keys.de().unwrap().0.len(), 1); + assert_eq!( + tokio::fs::read_to_string(ssh_dir.join("authorized_keys")) + .await + .unwrap(), + format!("{KEY}\n") + ); + } +} diff --git a/shared-libs/crates/start-core/src/version/mod.rs b/shared-libs/crates/start-core/src/version/mod.rs index d6d5d1394d..3fc29c3d29 100644 --- a/shared-libs/crates/start-core/src/version/mod.rs +++ b/shared-libs/crates/start-core/src/version/mod.rs @@ -907,7 +907,7 @@ mod tests { ("0.4.1.3", "0.4.2", 0), ("0.4.2", "0.4.2.1", 2), ("0.4.2.1", "0.4.2.2", 0), - ("0.4.2.2", "0.4.3", 1), + ("0.4.2.2", "0.4.3", 2), ] { let previous = from_value::(json!(from)) .unwrap() diff --git a/shared-libs/crates/start-core/src/version/v0_4_3.rs b/shared-libs/crates/start-core/src/version/v0_4_3.rs index 0e8c1a4f5e..e4c9b4a3c3 100644 --- a/shared-libs/crates/start-core/src/version/v0_4_3.rs +++ b/shared-libs/crates/start-core/src/version/v0_4_3.rs @@ -1,4 +1,5 @@ use exver::VersionRange; +use imbl_value::json; use super::v0_3_5::V0_3_0_COMPAT; use super::v0_4_0_2::for_each_host; @@ -25,12 +26,13 @@ impl VersionT for Version { V0_4_3.clone() } fn migration_revision(self) -> usize { - 1 + 2 } fn compat(self) -> &'static VersionRange { &V0_3_0_COMPAT } fn up(self, db: &mut Value, _: Self::PreUpRes) -> Result { + move_ssh_pubkeys(db, "private", "public")?; for_each_host(db, |host| { let Some(ranges) = host.get_mut("bindingRanges").and_then(Value::as_object_mut) else { return; @@ -43,11 +45,29 @@ impl VersionT for Version { }); Ok(Value::Null) } - fn down(self, _db: &mut Value) -> Result<(), Error> { - Ok(()) + fn down(self, db: &mut Value) -> Result<(), Error> { + move_ssh_pubkeys(db, "public", "private") } } +fn move_ssh_pubkeys(db: &mut Value, from: &str, to: &str) -> Result<(), Error> { + let keys = db + .get_mut(from) + .and_then(Value::as_object_mut) + .and_then(|source| source.remove("sshPubkeys")); + let destination = db + .as_object_mut() + .or_not_found("database")? + .entry(to.into()) + .or_insert_with(|| json!({})) + .as_object_mut() + .or_not_found("SSH key destination")?; + destination + .entry("sshPubkeys".into()) + .or_insert_with(|| keys.unwrap_or_else(|| json!({}))); + Ok(()) +} + /// Switches on the public IPs grouped with each enabled plain public domain of a range. /// The domain's forward already exposes them; earlier versions left them off after a renumber. fn group_enabled_plain_domains(addresses: &mut Value) { @@ -78,10 +98,67 @@ fn group_enabled_plain_domains(addresses: &mut Value) { #[cfg(test)] mod tests { - use imbl_value::json; + use patch_db::json_ptr::ROOT; use super::*; + #[test] + fn ssh_keys_move_without_changing_metadata_and_round_trip() { + let mut db = json!({ + "public": { "ui": { "snakeHighScore": 42 } }, + "private": { + "sshPrivkey": "private-key", + "sshPubkeys": { "fingerprint": { + "created_at": "2020-01-01T00:00:00Z", + "updated_at": "2021-01-01T00:00:00Z", + "value": "public-key" + } } + } + }); + let original = db.clone(); + Version.up(&mut db, ()).unwrap(); + assert_eq!( + db["public"]["sshPubkeys"], + original["private"]["sshPubkeys"] + ); + assert!(db["private"].get("sshPubkeys").is_none()); + assert_eq!(db["private"]["sshPrivkey"], json!("private-key")); + assert_eq!(db["public"]["ui"], original["public"]["ui"]); + let migrated = db.clone(); + Version.up(&mut db, ()).unwrap(); + assert_eq!(db, migrated); + Version.down(&mut db).unwrap(); + assert_eq!(db, original); + } + + #[tokio::test] + async fn same_version_upgrade_moves_legacy_keys_before_database_decode() { + use crate::db::model::Database; + + let account = + crate::account::AccountInfo::new("password", std::time::SystemTime::now(), None) + .unwrap(); + let mut fixture = to_value(&Database::init(&account, false, None, None).unwrap()).unwrap(); + fixture["public"] + .as_object_mut() + .unwrap() + .remove("sshPubkeys"); + fixture["public"]["serverInfo"]["latestMigrationRevision"] = json!(1); + fixture["private"]["sshPubkeys"] = json!({}); + let db = PatchDb::in_memory(); + db.put(&ROOT, &fixture).await.unwrap(); + Version.pre_init(&db).await.unwrap(); + let migrated = db.dump(&ROOT).await.value; + assert_eq!(migrated["public"]["sshPubkeys"], json!({})); + assert!(migrated["private"].get("sshPubkeys").is_none()); + assert_eq!( + migrated["public"]["serverInfo"]["latestMigrationRevision"], + json!(Version.migration_revision()) + ); + Version.pre_init(&db).await.unwrap(); + assert_eq!(db.dump(&ROOT).await.value, migrated); + } + fn row(hostname: &str, public: bool, metadata: Value) -> Value { json!({ "ssl": false, diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts b/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts index 0df25a9ea1..3357b0c93c 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/types.schemas.ts @@ -4796,6 +4796,31 @@ export const SshAddParams: z.ZodObject<{ key: typeof SshPubKey }> = id: 'SshAddParams', }) +/** + * Authorized-key intent shared by SSH mutations and subscribed clients. + */ +export const SshKeys: z.ZodRecord< + z.ZodString, + z.ZodObject<{ + created_at: z.ZodString + updated_at: z.ZodString + value: typeof SshPubKey + }> +> = /* @__PURE__ */ z + .record( + z.string(), + object({ + created_at: z.string(), + updated_at: z.string(), + value: SshPubKey, + }), + ) + .meta({ + id: 'SshKeys', + description: + 'Authorized-key intent shared by SSH mutations and subscribed clients.', + }) + /** * The public view of a backup found on a target: enough to identify it, and none of * [`BackupUnencryptedMetadata`]'s key material. @@ -7844,6 +7869,7 @@ export const AllPackageData: z.ZodRecord = export const Public: z.ZodObject<{ serverInfo: typeof ServerInfo packageData: typeof AllPackageData + sshPubkeys: z.ZodCodec, typeof SshKeys> registryCache: z.ZodCodec< z.ZodOptional>, z.ZodRecord @@ -7871,6 +7897,7 @@ export const Public: z.ZodObject<{ }> = /* @__PURE__ */ object({ serverInfo: ServerInfo, packageData: AllPackageData, + sshPubkeys: wire(SshKeys.optional(), SshKeys), registryCache: wire( z.record(z.string(), RegistryCache).optional(), z.record(z.string(), RegistryCache), diff --git a/shared-libs/ts-modules/start-core/lib/osBindings/types.ts b/shared-libs/ts-modules/start-core/lib/osBindings/types.ts index 62ce329bc4..f75b6d6ac0 100644 --- a/shared-libs/ts-modules/start-core/lib/osBindings/types.ts +++ b/shared-libs/ts-modules/start-core/lib/osBindings/types.ts @@ -1209,6 +1209,16 @@ export type SmtpValueInput = z.input export type SshAddParams = z.output export type SshAddParamsInput = z.input +/** + * Authorized-key intent shared by SSH mutations and subscribed clients. + */ +export type SshKeys = z.output + +/** + * Authorized-key intent shared by SSH mutations and subscribed clients. + */ +export type SshKeysInput = z.input + /** * The public view of a backup found on a target: enough to identify it, and none of * [`BackupUnencryptedMetadata`]'s key material. From 2606a12efd8caa0b0aad64cf3a013d0af92d03a6 Mon Sep 17 00:00:00 2001 From: sovsender <240553480+sovsender@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:31:37 -0500 Subject: [PATCH 37/38] fix(os): harden optical drive sync and SDK guards - sync nodes independently so one failure no longer blocks another drive, and never add over a stale node that could not be detached - plan() is a pure function with tests, including a node whose numbers change - the SDK requires StartOS 0.4.3 for opticalDrives and the pack wrapper fails when start-cli drops the flag, as for sharedVolumes - docs: restore the KVM section text that the Optical Drives section split, and document renumbering and raw SCSI access Co-Authored-By: Claude Sonnet 5.5 --- projects/start-sdk/check-cli.mjs | 4 ++ projects/start-sdk/docs/src/manifest.md | 13 +++-- .../start-sdk/lib/manifest/setupManifest.ts | 12 +++++ .../start-sdk/lib/test/setupManifest.test.ts | 36 ++++++++++++++ projects/start-sdk/pack.mjs | 14 +++--- shared-libs/crates/start-core/src/lxc/mod.rs | 37 +++++++++++---- .../crates/start-core/src/lxc/optical.rs | 47 +++++++++++++++++++ 7 files changed, 144 insertions(+), 19 deletions(-) diff --git a/projects/start-sdk/check-cli.mjs b/projects/start-sdk/check-cli.mjs index c5bab59c45..109ad797fb 100644 --- a/projects/start-sdk/check-cli.mjs +++ b/projects/start-sdk/check-cli.mjs @@ -10,6 +10,10 @@ const { manifest } = createRequire(import.meta.url)( resolve('javascript/index.js'), ) export const requiresSharedVolumes = !!manifest.sharedVolumes +// Capabilities a start-cli that predates them silently drops while packing. +export const preservedCapabilities = ['sharedVolumes', 'opticalDrives'].filter( + (key) => manifest[key] === true, +) function checkCli() { if (!requiresSharedVolumes) return diff --git a/projects/start-sdk/docs/src/manifest.md b/projects/start-sdk/docs/src/manifest.md index 21cbce604d..c45daf1143 100644 --- a/projects/start-sdk/docs/src/manifest.md +++ b/projects/start-sdk/docs/src/manifest.md @@ -350,6 +350,11 @@ When set, StartOS exposes `/dev/kvm` inside the service's container, so the gues > [!IMPORTANT] > The granted node belongs to the container's root and carries the permissions the server gives it, which on `/dev/kvm` are `0660`. **Run the process that opens it as root**, as the GPU packages do for `hardwareAcceleration` — that is the only arrangement StartOS guarantees. +The device appears only on a server whose CPU supports virtualization and whose kernel has KVM active for it. Where it does not, the service starts as normal with no `/dev/kvm` — so a service that can fall back to software emulation should test for the device and do so, and one that cannot should declare a health check saying this server does not support KVM. Give that check `gracePeriod: 0`, so it reports the reason instead of `starting`, and `sdk.trigger.onceTrigger` — the default re-polls a failing check every second for the life of the service. See [Health Checks](./main.md#health-checks). + +> [!WARNING] +> `/dev/kvm` is a direct interface to the host kernel's hypervisor, so it widens the kernel attack surface reachable from the service. Enable it only for a service that genuinely runs virtual machines. + ### Optical Drives For services that read discs, such as ripping or archiving tools, set `opticalDrives: true` at the manifest top level: @@ -358,15 +363,15 @@ For services that read discs, such as ripping or archiving tools, set `opticalDr opticalDrives: true, ``` -When set, StartOS exposes the server's optical drives inside the service's container: the block node `/dev/srN` and its SCSI generic node `/dev/sgN`. A drive connected while the service runs appears within seconds, and the nodes of a drive that is disconnected are removed. Other disks, even on the same controller, are never exposed. +When set, StartOS exposes the server's optical drives inside the service's container: the block node `/dev/srN` and its SCSI generic node `/dev/sgN`. A drive connected while the service runs appears within a few seconds, and the nodes of a drive that is disconnected are removed. Other disks, even on the same controller, are never exposed. The capability requires StartOS 0.4.3; `buildManifest` rejects an explicit older `osVersion`. + +The numbers are not stable: a drive that is unplugged and plugged in again can come back as `/dev/sr1` and `/dev/sg1`. Look for `/dev/sr*` and `/dev/sg*` instead of hard-coding `sr0`. > [!IMPORTANT] > Like `/dev/kvm`, the nodes belong to the container's root with mode `0660`. **Run the process that opens them as root.** -The device appears only on a server whose CPU supports virtualization and whose kernel has KVM active for it. Where it does not, the service starts as normal with no `/dev/kvm` — so a service that can fall back to software emulation should test for the device and do so, and one that cannot should declare a health check saying this server does not support KVM. Give that check `gracePeriod: 0`, so it reports the reason instead of `starting`, and `sdk.trigger.onceTrigger` — the default re-polls a failing check every second for the life of the service. See [Health Checks](./main.md#health-checks). - > [!WARNING] -> `/dev/kvm` is a direct interface to the host kernel's hypervisor, so it widens the kernel attack surface reachable from the service. Enable it only for a service that genuinely runs virtual machines. +> The SCSI generic node accepts any command the drive understands, including firmware writes. Enable `opticalDrives` only for a service that genuinely reads or writes discs. ### Multiple Images diff --git a/projects/start-sdk/lib/manifest/setupManifest.ts b/projects/start-sdk/lib/manifest/setupManifest.ts index ee7e1eb4c3..1769a5d3fc 100644 --- a/projects/start-sdk/lib/manifest/setupManifest.ts +++ b/projects/start-sdk/lib/manifest/setupManifest.ts @@ -44,6 +44,7 @@ export function setupManifest< } const sharedVolumeOsVersion = '0.4.3' +const opticalDriveOsVersion = '0.4.3' function manifestOsVersion(manifest: SDKManifest): string { const required = manifest.sharedVolumes ? sharedVolumeOsVersion : OSVersion @@ -55,6 +56,17 @@ function manifestOsVersion(manifest: SDKManifest): string { ) { throw new Error(`Shared volumes require StartOS ${required} or later`) } + // An older StartOS ignores the flag, so the service would install and silently get no drive. + if ( + manifest.opticalDrives && + StartOsVersion.parse(requested).compare( + StartOsVersion.parse(opticalDriveOsVersion), + ) === 'less' + ) { + throw new Error( + `Optical drives require StartOS ${opticalDriveOsVersion} or later`, + ) + } return requested } diff --git a/projects/start-sdk/lib/test/setupManifest.test.ts b/projects/start-sdk/lib/test/setupManifest.test.ts index 46a8d5ef31..2c64af7386 100644 --- a/projects/start-sdk/lib/test/setupManifest.test.ts +++ b/projects/start-sdk/lib/test/setupManifest.test.ts @@ -170,6 +170,42 @@ test('an explicit compatibility override cannot understate shared-volume support ).toBe('0.4.3') }) +test('optical-drive capability defaults to false and preserves explicit opt-in', () => { + expect( + buildManifest({ + versionGraph: versions, + manifest: manifest(), + dependencies: Dependencies.of(), + i18n, + }).opticalDrives, + ).toBe(false) + const built = buildManifest({ + versionGraph: versions, + manifest: setupManifest({ ...manifest(), opticalDrives: true }), + dependencies: Dependencies.of(), + i18n, + }) + expect(built.opticalDrives).toBe(true) + expect(built.osVersion).toBe('0.4.3') +}) + +test('an explicit compatibility override cannot understate optical-drive support', () => { + for (const osVersion of ['0.4.2', '0.4.1.1']) { + expect(() => + buildManifest({ + versionGraph: versions, + manifest: setupManifest({ + ...manifest(), + opticalDrives: true, + osVersion, + }), + dependencies: Dependencies.of(), + i18n, + }), + ).toThrow('Optical drives require StartOS 0.4.3 or later') + } +}) + test('the default locale is the given package i18n default language', () => { const own = setupI18n({}, {}, 'fr_FR') setupI18n({}, {}, 'de_DE') diff --git a/projects/start-sdk/pack.mjs b/projects/start-sdk/pack.mjs index 7717886c34..a2bb8df613 100644 --- a/projects/start-sdk/pack.mjs +++ b/projects/start-sdk/pack.mjs @@ -1,14 +1,14 @@ #!/usr/bin/env node import { execFileSync } from 'node:child_process' import { rmSync } from 'node:fs' -import { requiresSharedVolumes } from './check-cli.mjs' +import { preservedCapabilities } from './check-cli.mjs' const [output, ...args] = process.argv.slice(2) try { execFileSync('start-cli', ['s9pk', 'pack', ...args, '-o', output], { stdio: 'inherit', }) - if (requiresSharedVolumes) { + if (preservedCapabilities.length) { const manifest = JSON.parse( execFileSync( 'start-cli', @@ -18,10 +18,12 @@ try { }, ), ) - if (manifest.sharedVolumes !== true) - throw new Error( - 'The packer did not preserve sharedVolumes. Upgrade start-cli to a volume-capable build.', - ) + for (const key of preservedCapabilities) { + if (manifest[key] !== true) + throw new Error( + `The packer did not preserve ${key}. Upgrade start-cli to a build that supports it.`, + ) + } } } catch (error) { rmSync(output, { force: true }) diff --git a/shared-libs/crates/start-core/src/lxc/mod.rs b/shared-libs/crates/start-core/src/lxc/mod.rs index f8bf4e2612..7df8b255a9 100644 --- a/shared-libs/crates/start-core/src/lxc/mod.rs +++ b/shared-libs/crates/start-core/src/lxc/mod.rs @@ -733,24 +733,43 @@ async fn sync_optical_drives( applied: &mut BTreeSet, ) -> Result<(), Error> { let desired = optical::scan(Path::new("/sys")).await; - let removed = applied.difference(&desired).cloned().collect::>(); + let (removed, added) = optical::plan(applied, &desired); + // A failure on one node must not hold up the others (a second drive, or a removal), so keep + // going and report the first error. A failed node stays unapplied and retries on the next tick. + let mut first_err = None; + let mut stuck = BTreeSet::new(); for node in removed { - detach_node(guid, rootfs, &node.path).await?; - applied.remove(&node); + match detach_node(guid, rootfs, &node.path).await { + Ok(()) => { + applied.remove(&node); + } + Err(e) => { + stuck.insert(node.path); + first_err.get_or_insert(e); + } + } } - let added = desired.difference(applied).cloned().collect::>(); for node in added { - if let Err(e) = LxcContainer::mknod_in( + // `mknod_in` treats a node already at the path as the new one, so never add over a + // stale node that could not be detached. + if stuck.contains(&node.path) { + continue; + } + match LxcContainer::mknod_in( guid, rootfs, &node.path, node.ty, node.major, node.minor, 0o660, ) .await { - detach_node(guid, rootfs, &node.path).await.log_err(); - return Err(e); + Ok(()) => { + applied.insert(node); + } + Err(e) => { + detach_node(guid, rootfs, &node.path).await.log_err(); + first_err.get_or_insert(e); + } } - applied.insert(node); } - Ok(()) + first_err.map_or(Ok(()), Err) } async fn detach_node(guid: &str, rootfs: &Path, path: &Path) -> Result<(), Error> { diff --git a/shared-libs/crates/start-core/src/lxc/optical.rs b/shared-libs/crates/start-core/src/lxc/optical.rs index 81ed3e04ea..787ca827ae 100644 --- a/shared-libs/crates/start-core/src/lxc/optical.rs +++ b/shared-libs/crates/start-core/src/lxc/optical.rs @@ -75,6 +75,18 @@ pub async fn scan(sys: &Path) -> BTreeSet { nodes } +/// The nodes to detach, then the nodes to attach, to take `applied` to `desired`. A drive whose +/// node keeps its path but changes numbers is in both lists, so detach before attaching. +pub fn plan( + applied: &BTreeSet, + desired: &BTreeSet, +) -> (Vec, Vec) { + ( + applied.difference(desired).cloned().collect(), + desired.difference(applied).cloned().collect(), + ) +} + #[cfg(test)] mod tests { use super::*; @@ -138,4 +150,39 @@ mod tests { let sys = tempfile::tempdir().unwrap(); assert!(scan(&sys.path().join("absent")).await.is_empty()); } + + #[tokio::test] + async fn the_block_node_appears_before_the_generic_one() { + // `sg` can load after `sr`; the generic node is then picked up by a later scan. + let sys = tempfile::tempdir().unwrap(); + let root = sys.path(); + write(root, "class/block/sr0/dev", "11:0\n"); + write(root, "class/block/sr0/device/type", "5\n"); + + assert_eq!(scan(root).await, BTreeSet::from([node("/dev/sr0", 'b', 11, 0)])); + } + + #[test] + fn plan_adds_and_removes_only_what_changed() { + let sr0 = node("/dev/sr0", 'b', 11, 0); + let sg0 = node("/dev/sg0", 'c', 21, 0); + let sr1 = node("/dev/sr1", 'b', 11, 1); + let applied = BTreeSet::from([sr0.clone(), sg0.clone()]); + + assert_eq!(plan(&applied, &applied), (vec![], vec![])); + assert_eq!(plan(&BTreeSet::new(), &applied), (vec![], vec![sr0.clone(), sg0.clone()])); + assert_eq!(plan(&applied, &BTreeSet::new()), (vec![sr0.clone(), sg0.clone()], vec![])); + assert_eq!(plan(&applied, &BTreeSet::from([sg0, sr1.clone()])), (vec![sr0], vec![sr1])); + } + + #[test] + fn plan_replaces_a_node_whose_numbers_changed() { + let old = node("/dev/sg0", 'c', 21, 0); + let new = node("/dev/sg0", 'c', 21, 5); + + assert_eq!( + plan(&BTreeSet::from([old.clone()]), &BTreeSet::from([new.clone()])), + (vec![old], vec![new]) + ); + } } From ec90d95043aaa1d25875e3ab104ea6822a420097 Mon Sep 17 00:00:00 2001 From: sovsender <240553480+sovsender@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:43:20 -0500 Subject: [PATCH 38/38] ci: skip jobs that need Start9's credentials on forks Create Docker Image pushes to ghcr.io/start9labs and Migration Image downloads a release only Start9's repository has, so both failed on every fork build. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/build-products.yaml | 3 ++- .github/workflows/startos-image.yaml | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-products.yaml b/.github/workflows/build-products.yaml index ba9896ac47..c0e4d305ec 100644 --- a/.github/workflows/build-products.yaml +++ b/.github/workflows/build-products.yaml @@ -271,7 +271,8 @@ jobs: registry-image: name: Create Docker Image needs: [changes, build] - if: ${{ !cancelled() && needs.changes.outputs.start-registry == 'true' && needs.build.result == 'success' }} + # Pushes to ghcr.io/start9labs, which only Start9's org can do. + if: ${{ !cancelled() && needs.changes.outputs.start-registry == 'true' && needs.build.result == 'success' && github.repository_owner == 'Start9Labs' }} env: PUSH_IMAGE: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }} permissions: diff --git a/.github/workflows/startos-image.yaml b/.github/workflows/startos-image.yaml index 064799b892..5c904fe58e 100644 --- a/.github/workflows/startos-image.yaml +++ b/.github/workflows/startos-image.yaml @@ -176,7 +176,8 @@ jobs: migration: name: Migration Image needs: [build] - if: contains(fromJson('["x86_64", "x86_64-nonfree", "aarch64", "aarch64-nonfree"]'), inputs.platform) + # Downloads a release of the previous version, which only Start9's repository has. + if: github.repository_owner == 'Start9Labs' && contains(fromJson('["x86_64", "x86_64-nonfree", "aarch64", "aarch64-nonfree"]'), inputs.platform) runs-on: ubuntu-latest env: GH_TOKEN: ${{ github.token }}