Compare commits

...
2 Commits
32 changed files with 2325 additions and 2255 deletions

No files matched your search

+2 -4
View File
@@ -15,13 +15,11 @@ jobs:
uses: actions/checkout@v6
- name: Build package
working-directory: debian-package
run: ./build.sh
run: ./build.py
- name: Publish package
working-directory: debian-package
env:
SERVER_URL: ${{ secrets.CI_URL }}
OWNER: ${{ secrets.CI_OWNER }}
PACKAGES_TOKEN: ${{ secrets.CI_TOKEN }}
run: ./publish.sh
run: ./publish.py
+1 -1
View File
@@ -16,6 +16,6 @@ node_modules
web/dist
.venv
dev.json
/.dev-build.serial
**/.env
/.lm-dev-config/
/debian-package/debian/changelog
+53 -18
View File
@@ -1408,19 +1408,30 @@ one line with its type and message.
Consequences: The logs hold one line per failure, without its stack. A failure that reaches the
last line of defence is found by its message and fixed where it occurs, with its own handling.
## ADR-49: A changelog summary is a paragraph wrapped at 80 columns
## ADR-49: CHANGELOG.md is the history, and debian/changelog is written from it by the build
Status: Accepted
Context: The summary of an entry of `debian/changelog` is the commit message of its release,
which `release.py` reads from the changelog. Summaries are often longer than the 80 columns
Debian's tools expect of a changelog line.
Context: The history of the package is also the source of each release's commit message and tag:
`release.py` commits with the summary of the newest entry and tags its version. A Debian changelog
needs a package name, a maintainer, an RFC 2822 date and lines of at most 80 columns in every entry,
which a history written by hand gets wrong and which repeat in every entry. Summaries are often
longer than one line.
Decision: The summary is the entry's first paragraph, indented by two spaces and wrapped at 80
columns. `release.py` joins its lines with single spaces into the commit message.
Decision: `CHANGELOG.md` at the repository's root is the only history kept by hand. An entry is a
`## x.y.z` heading, a summary paragraph wrapped at 100 columns and `-` items; `release.py` writes
the release time into the heading, `## x.y.z - YYYY-MM-DD HH:MM:SS +ZZZZ`, when it commits the
entry, joining the summary's lines with single spaces into the commit message. `bin/changelog.py`
writes `debian/changelog` from it in the build image, with the package name and the maintainer of
`debian/control`, the time of the build for an entry without a date, and `DEB_VERSION` as the
newest entry's version for a dev build. `x.y.z` is the Debian version `x.y.z-1`, and `x.y.z-n` is
itself. `debian/changelog` is not kept in the repository.
Consequences: The commit message is one line however the summary is wrapped, so a summary
rewrapped later still matches the commit of its release.
Consequences: The commit message is one line however the summary is wrapped, so a summary rewrapped
later still matches the commit of its release, and an entry with a date in its heading is
released. Every entry of the generated `debian/changelog` has the current package name and
maintainer, also the entries made under the package's earlier name. The builder image has Python
for the script.
## ADR-50: The help is Markdown rendered in the browser, in a panel that pushes the page
@@ -1473,7 +1484,7 @@ Status: Accepted
Context: With `terraform_dir`, the manager built `http://<router_private_ip_addresses.int>:7081`.
The port of the server's web service is `web.port` and the interfaces it listens on are `web.listen`,
which the platform sets from its variables; the manager that `dev.sh` runs on a workstation cannot read them.
which the platform sets from its variables; the manager that `dev.py` runs on a workstation cannot read them.
Decision: `router_url` is the output `router_web_url` of the platform, which derives the URL from
the same variables that configure the server.
@@ -1559,7 +1570,7 @@ programs are in `/usr/lib/linux-manager`, the Manager's application and help in
state of the upgrades in `/var/lib/linux-manager`. The Manager's unit is
`linux-manager-ui.service`. The debconf questions of its first administrator are
`linux-manager/admin_username` and `admin_password`. The server's bootstrap page shows the
Manager, which has no bootstrap service of its own. `dev.sh` runs the Manager on a workstation,
Manager, which has no bootstrap service of its own. `dev.py` runs the Manager on a workstation,
with `terraform_dir` and `bind`.
Consequences: The repository holds the Manager's `web/` and `docs/`, and its build runs from the
@@ -1621,16 +1632,16 @@ own (`features.networks`), a WAN and two LANs, and a container `repo` that serve
repository, `resolute main`, built with `apt-ftparchive` and signed by its own key. The networks
are OVN networks on an uplink bridge of the remote, as OVN is the only network type LXD creates
inside a project; they belong to the project and go with it. `bin/lm-dev-build.py` builds the newest
changelog entry as `<upstream>~dev<N>-<revision>`, `N` counted in `.dev-build.serial`, which a
release sets to 0, by passing `DEB_VERSION` to the build, which rewrites the version in the image
only, and publishes the build in that repository. `bin/lm-dev-vm.py` gives a VM of the project
that repository as its apt source. The project also has a Vault, through which secrets reach its
instances (ADR-61). The scripts keep their state in `.lm-dev-config/`, which outlives clean-ups of
`tmp/`. The automated tests (`lm-dev-run.py`) keep their own project for one run and install from a
file.
changelog entry as `<upstream>~dev<N>-<revision>`, `N` counted in `LXD_DEV_BUILD_SERIAL` of
`.lm-dev-config/settings.json`, which a release sets to 0, by passing `DEB_VERSION` to the build,
which rewrites the version in the image only, and publishes the build in that repository.
`bin/lm-dev-vm.py` gives a VM of the project that repository as its apt source. The project also
has a Vault, through which secrets reach its instances (ADR-61). The scripts keep their state in
`.lm-dev-config/`, which outlives clean-ups of `tmp/`. The automated tests (`lm-dev-run.py`) keep
their own project for one run and install from a file.
Consequences: Every dev build is an apt update of the one before, and the release of the entry,
which sorts above all of its `~dev` builds, is an update of them all. The changelog is not
which sorts above all of its `~dev` builds, is an update of them all. `CHANGELOG.md` is not
changed by a dev build. Dev builds go to `out/dev/`, so `out/` holds only release builds.
## ADR-59: A Simple CA root signs the issuing CAs through a sign-ca token of its issuing CA
@@ -1785,3 +1796,27 @@ Consequences: A change made during a run is applied by the extra run that follow
A plain `systemctl restart linux-manager-setup` still kills a run in progress; the documentation
names `linux-manager-config-edit apply` instead. A run that fails runs once more when a request came
during it, and the unit's result is that of the last run.
## ADR-64: The schema is two LDIF files, and the PKI part is a schema of its own
Status: Accepted
Context: An application other than Linux Manager, such as Simple CA, is to keep its CAs in OpenLDAP
in Linux Manager's PKI classes, either on the server's own slapd or on a slapd without Linux
Manager. The second needs the PKI's definitions as a file its administrator can load, without the
account, OpenID Provider and role classes. The first needs an account other than root that may
read and write the keys, which no account could.
Decision: The schema is defined only in two LDIF files of `/usr/share/linux-manager/schema/`, in the
form `ldapadd` loads into `cn=config`: `linux-manager-pki.ldif` (`cn=linux-manager-pki`), the CAs,
the certificates and the host certificates, which needs only the core schema, and
`linux-manager.ldif` (`cn=linux-manager`), the rest. Setup loads each into its own schema entry, the
same way a slapd without Linux Manager loads the PKI file. A certificate may name what it is filed
under with `linuxManagerCertificateName`, which Linux Manager does not set. The members of the group
`pki-managers` may manage `ou=pki` with its keys; an application binds as a service account in that
group. On a slapd without Linux Manager, access is that slapd's administrator's business.
Consequences: One file serves both kinds of slapd, so the definitions cannot drift apart. The group
is an ordinary one, made with its first member; until it exists, only root reads the keys, and
renaming it takes the access away. A server whose slapd holds the PKI definitions inside
`cn=linux-manager` is installed anew, as slapd refuses the same OIDs in a second entry.
+1341
View File
File diff suppressed because it is too large. Load diff
+4 -2
View File
@@ -18,15 +18,17 @@ RUN apt-get -o Acquire::Retries=5 update \
dpkg-dev \
debhelper \
lintian \
python3 \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /build
COPY debian-package/ src/
COPY docs/ src/docs/
COPY --from=web /web/dist src/web/dist/
# DEB_VERSION, when set, replaces the version of the newest changelog entry in the image only.
# debian/changelog is written from CHANGELOG.md; DEB_VERSION, when set, is the version of its newest entry.
COPY CHANGELOG.md bin/changelog.py ./
ARG DEB_VERSION
RUN if [ -n "$DEB_VERSION" ]; then sed -i "1s/([^)]*)/($DEB_VERSION)/" src/debian/changelog; fi
RUN python3 changelog.py CHANGELOG.md src/debian/control src/debian/changelog ${DEB_VERSION:+--version "$DEB_VERSION"}
RUN cd src && dpkg-buildpackage -us -uc -b
RUN lintian --no-tag-display-limit /build/*.changes || true
+33 -2
View File
@@ -162,7 +162,10 @@ Table of Contents
6.2. LDAP Attribute Types
Every attribute type below has the status active, was allocated on
2026-11-21, and is defined in "linuxmanager_ldap.py" of this
2026-11-21 unless its entry gives another date, and is defined in
"linux-manager-pki.ldif" (the PKI: .2.1.2 to .2.1.12 and .2.1.24 to
.2.1.28) or "linux-manager.ldif" (the others) in
"debian-package/src/usr/share/linux-manager/schema/" of this
repository.
.2.1.1 linuxManagerScope
@@ -236,10 +239,34 @@ Table of Contents
.2.1.23 linuxManagerResourceScope
A scope of a resource of the OpenID Provider
.2.1.24 linuxManagerToken
The Simple CA token that signs the issuing CAs
Allocated: 2026-11-23
.2.1.25 linuxManagerUpstreamName
The Simple CA issuing CA of the token
Allocated: 2026-11-23
.2.1.26 linuxManagerCertificateChain
A certificate and its chain, PEM
Allocated: 2026-11-24
.2.1.27 linuxManagerRequestKey
The private key of a CSR, PEM
Allocated: 2026-11-24
.2.1.28 linuxManagerCertificateName
The name a certificate is filed under by the application
that keeps it
Allocated: 2026-11-24
6.3. LDAP Object Classes
Every object class below has the status active, was allocated on
2026-11-21, and is defined in "linuxmanager_ldap.py" of this
2026-11-21 unless its entry gives another date, and is defined in
"linux-manager-pki.ldif" (.2.2.2, .2.2.3 and .2.2.5) or
"linux-manager.ldif" (.2.2.1 and .2.2.4) in
"debian-package/src/usr/share/linux-manager/schema/" of this
repository.
.2.2.1 linuxManagerAccount
@@ -254,6 +281,10 @@ Table of Contents
.2.2.4 linuxManagerRole
Structural: a role of a resource of the OpenID Provider
.2.2.5 linuxManagerHostCertificate
Structural: a certificate of the server kept with its key
Allocated: 2026-11-24
7. Requesting an OID
An allocation is a change to this document. The change adds an
+66 -16
View File
@@ -497,14 +497,37 @@ A CA entry (class `linuxManagerAuthority`) has its certificate (`cACertificate;b
(`certificateRevocationList;binary`) and CRL number. A certificate entry (class
`linuxManagerCertificate`) has the certificate (`userCertificate;binary`), its kind (`ca`, `router`,
`user` or `external`), template, names, expiry and revocation, and for the server's and the users'
certificates the key. A user's certificate is also the `userCertificate` of the user's entry. No
account of the directory reads a key (`linuxManagerPrivateKey`); only root does, through the local
socket. `slapcat` writes the whole PKI into every backup with the users.
certificates the key. A user's certificate is also the `userCertificate` of the user's entry. A
certificate may also have `linuxManagerCertificateName`, the name an application other than Linux
Manager files it under; Linux Manager does not set it. Keys (`linuxManagerPrivateKey`) are read by
root, through the local socket, and by the members of the group `pki-managers`; no other account
reads them. `slapcat` writes the whole PKI into every backup with the users.
```sh
ldapsearch -Q -Y EXTERNAL -H ldapi:/// -b ou=pki,dc=linux-manager,dc=local -s one cn
```
### The PKI schema in another application
The PKI's classes and attributes are a schema of their own, `linux-manager-pki`, in
`/usr/share/linux-manager/schema/linux-manager-pki.ldif`; it needs only slapd's core schema. An
application that keeps its CAs in LDAP, such as Simple CA, uses it in one of two ways:
- **On the server's slapd.** The application binds as a service account of the server, which is a
member of `pki-managers`; the members of that group read and write `ou=pki` with its keys. The
group is made with its first member, and renaming it takes the access away:
```sh
linux-manager-group add pki-managers --member simple-ca
```
- **On a slapd without Linux Manager.** Its administrator loads the schema and grants the identity
the application binds as, such as the database's administrator, the access it needs:
```sh
ldapadd -Y EXTERNAL -H ldapi:/// -f linux-manager-pki.ldif
```
### The CAs
The root signs the issuing CAs only (path length 1), and the issuing CAs sign the certificates
@@ -773,8 +796,10 @@ is switched on:
password;
- `ou=users` holds one entry per user, named by `uid`: an `inetOrgPerson` for a VPN user, an
`account` for a Manager-only account (see Managing users);
- the package's own schema, `cn=linux-manager,cn=schema,cn=config`, under the OID
`1.3.6.1.4.1.67380.10.1.2`, listed in `OID-REGISTRY.txt`: the auxiliary class
- the package's own schema under the OID `1.3.6.1.4.1.67380.10.1.2`, listed in
`OID-REGISTRY.txt`, in two schema entries loaded from `/usr/share/linux-manager/schema/`:
`cn=linux-manager-pki,cn=schema,cn=config`, the PKI (see Certificates), and
`cn=linux-manager,cn=schema,cn=config`, the accounts, with the auxiliary class
`linuxManagerAccount`, which Manager-only and service accounts have, and the attribute
`linuxManagerScope`, authorization scopes, of which `service` marks a service account;
`displayName` and `description` are the display name and the description of a service
@@ -2543,9 +2568,9 @@ PostgreSQL is not running yet.
| `router_url` | The server's status web service | On the server, `http://127.0.0.1:7091`, the web service behind Caddy |
| `database` | A PostgreSQL connection string for the sessions | The `linux-manager-ui` database on the server |
| `listen` | On the server, the interfaces the firewall opens `port` on: `internal`, `external` or `both` | `both` |
| `bind` | The one address to listen on, with `port`, off the server, as `dev.sh` sets it | none; on the server `127.0.0.1:7090` |
| `bind` | The one address to listen on, with `port`, off the server, as `dev.py` sets it | none; on the server `127.0.0.1:7090` |
| `port` | The port of `bind`; on the server, Caddy's plain HTTP port of the manager, which redirects to the HTTPS address while HTTPS is on unless `https.disable_auto_redirect` is `true` | `7080` |
| `terraform_dir` | A Terraform root directory whose outputs give `router_url` when it is not set; `dev.sh` sets it | none |
| `terraform_dir` | A Terraform root directory whose outputs give `router_url` when it is not set; `dev.py` sets it | none |
| `iac_tool` | The tool that reads the outputs of `terraform_dir`: `terraform` or `tofu` | `terraform` |
From the outputs of `<iac_tool> -chdir=<terraform_dir> output -json`, read every 30 seconds at
@@ -2577,20 +2602,20 @@ echo 'linux-manager linux-manager/admin_password password s3cr3t-pass' | debconf
### Running the application on a workstation
`dev.sh` runs the manager and the Vite development server, which reloads on changes, on the
`dev.py` runs the manager and the Vite development server, which reloads on changes, on the
workstation; the application is at http://localhost:5180. Its first argument is the
`config.json` of the platform that deployed the server. Its `module_root`, relative to the
directory of that file, is the Terraform root module whose outputs give the server's address.
The second argument, optional, is the connection string of a PostgreSQL database for the
sessions; without it the sessions are kept in the database `PGDATABASE` names, or the one named
after the login, and libpq takes the server, port, user, password and SSL mode from the `PG*`
variables of the environment, such as those of the platform's `pg.env.sh`. `dev.sh` writes them
variables of the environment, such as those of the platform's `pg.env.sh`. `dev.py` writes them
as `terraform_dir` and `database`, with the platform's `iac_tool` and `bind` `127.0.0.1`, to `dev.json` in the repository root, which is not in Git, and
the manager reads that and listens on `127.0.0.1:7080`:
```sh
./dev.sh /path/to/azure-platform/config.json
./dev.sh /path/to/azure-platform/config.json 'host=localhost dbname=manager user=manager password=secret'
./dev.py /path/to/azure-platform/config.json
./dev.py /path/to/azure-platform/config.json 'host=localhost dbname=manager user=manager password=secret'
```
It creates `.venv` with `psycopg[binary]` and `requests` when they are missing, and installs the npm dependencies
@@ -2635,7 +2660,7 @@ key pair, everything under `/etc/swanctl`, the folders of the web sites in `/var
## Building
```sh
./build.sh
./build.py
```
The build runs in a container from the repository root: a Node.js stage builds the
@@ -2645,9 +2670,34 @@ container runtime is Apple's `container` on macOS and Docker on Linux, or `CONTA
when set, for example Docker on a remote engine:
```sh
CONTAINER_RUNTIME=docker DOCKER_CONTEXT=build-host ./build.sh
CONTAINER_RUNTIME=docker DOCKER_CONTEXT=build-host ./build.py
```
`./publish.sh` uploads the package to the component `main` of the distribution `resolute`
(Ubuntu 26.04, the only supported release) of the configured repository, skipping a
distribution that has the version already; `DISTRIBUTIONS` names others.
The build writes `debian/changelog` from `CHANGELOG.md` with `bin/changelog.py`; the file is
not kept in the repository.
`./publish.py` uploads the package of the newest `CHANGELOG.md` entry from `out/` to the
component `main` of the distribution `resolute` (Ubuntu 26.04, the only supported release) of the
Gitea Debian repository of `OWNER` at `SERVER_URL`, with the token `PACKAGES_TOKEN` or else the
content of `~/.gitea-packages-token`, skipping a distribution that has the version already;
`DISTRIBUTIONS` names others.
## Releasing
`CHANGELOG.md` is the package's history. Its newest entry, a `## x.y.z` heading, a summary
paragraph and `-` items, is the next release; `x.y.z` is the Debian version `x.y.z-1`, and
`x.y.z-n` is a later release of the same code.
```sh
./release.py
./release.py --push
./release.py --no-tag --push
./release.py -n --push
```
`./release.py` writes the current time into the newest entry's heading, `## x.y.z - YYYY-MM-DD
HH:MM:SS +ZZZZ`, and commits everything with the entry's summary as the message; the release stays
on the machine, and the next change needs a new entry. `--push` also tags the version, `x.y.z` or
`x.y.z-n`, and pushes `main` and the tag, which starts the release workflow; a committed entry is
pushed this way later too. `--no-tag` makes an internal release: `--push` then pushes `main` alone.
`-n` prints the heading and the git commands instead of making them.
+119
View File
@@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""Read CHANGELOG.md and write debian/changelog from it: changelog.py CHANGELOG CONTROL OUTPUT [--version V].
CHANGELOG.md is the history of the package. Its entries, newest first, are "## VERSION" headings,
"## VERSION - YYYY-MM-DD HH:MM:SS +ZZZZ" once released, each followed by a summary paragraph and
"- " items whose continuation lines are indented by two spaces; an older entry may have items only.
VERSION x.y.z is the Debian version x.y.z-1, and x.y.z-n, n from 2, is x.y.z-n.
The command writes OUTPUT in Debian's format: the package name (Source) and the maintainer
(Maintainer) of the debian/control CONTROL, the summary and the items wrapped at 80 columns, and the
entry's date, the current time for an entry without one. --version replaces the Debian version of
the newest entry, as the dev builds do. A malformed CHANGELOG.md is a message on standard error and
the exit status 1.
"""
import argparse
import datetime
import email.utils
import pathlib
import re
import sys
import textwrap
#: The format of the date in a heading.
DATE_FORMAT = '%Y-%m-%d %H:%M:%S %z'
#: A heading: its version, and its date once the entry is released.
HEADING = re.compile(r'## (\d+\.\d+\.\d+(?:-\d+)?)(?: - (\d{4}-\d\d-\d\d \d\d:\d\d:\d\d [+-]\d{4}))?$')
def entries(text):
"""The entries of the CHANGELOG.md text, newest first: dicts of version, date (a datetime or None), summary (a
string or None), items (strings) and line, the index of the heading's line; ValueError when it is malformed."""
found = []
# Where the entry is: right after its heading, in its summary, after the summary, or in its items.
state = None
for index, line in enumerate(text.splitlines()):
if line.startswith('## '):
match = HEADING.match(line)
if not match:
raise ValueError(f'line {index + 1}: a heading is "## x.y.z" or "## x.y.z - {DATE_FORMAT}": {line}')
date = datetime.datetime.strptime(match.group(2), DATE_FORMAT) if match.group(2) else None
found.append({'version': match.group(1), 'date': date, 'summary': None, 'items': [], 'line': index})
state = 'heading'
elif state is None:
continue
elif not line.strip():
state = 'after' if state == 'summary' else state
elif line.startswith('- '):
found[-1]['items'].append(line[2:].strip())
state = 'items'
elif line.startswith(' ') and state == 'items':
found[-1]['items'][-1] += ' ' + line.strip()
elif state in ('heading', 'summary'):
found[-1]['summary'] = f'{found[-1]["summary"]} {line.strip()}' if state == 'summary' else line.strip()
state = 'summary'
else:
raise ValueError(f'line {index + 1}: neither a summary line, an item nor its continuation: {line}')
return found
def debian_version(version):
"""The Debian version of a CHANGELOG.md version: x.y.z-1 for x.y.z, x.y.z-n as it is."""
return version if '-' in version else f'{version}-1'
def wrapped(text, first, rest):
"""The text wrapped at 80 columns, its first line indented by first and the others by rest."""
return textwrap.fill(text, width=80, initial_indent=first, subsequent_indent=rest, break_long_words=False,
break_on_hyphens=False)
def debian(found, package, maintainer, version=None):
"""The debian/changelog of the entries, with the version as the newest entry's Debian version when given."""
blocks = []
for index, entry in enumerate(found):
number = version if index == 0 and version else debian_version(entry['version'])
date = entry['date'] or datetime.datetime.now().astimezone()
lines = [f'{package} ({number}) unstable; urgency=medium', '']
if entry['summary']:
lines += [wrapped(entry['summary'], ' ', ' '), '']
lines += [wrapped(item, ' * ', ' ') for item in entry['items']]
if entry['items']:
lines.append('')
lines.append(f' -- {maintainer} {email.utils.format_datetime(date)}')
blocks.append('\n'.join(lines) + '\n')
return '\n'.join(blocks)
def control_field(text, name):
"""The value of the field name of the source paragraph of the debian/control text."""
match = re.search(rf'^{name}:\s*(.+)$', text.split('\n\n', 1)[0], re.MULTILINE)
if not match:
raise ValueError(f'debian/control has no {name}')
return match.group(1).strip()
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('changelog', type=pathlib.Path, help='CHANGELOG.md')
parser.add_argument('control', type=pathlib.Path, help='debian/control')
parser.add_argument('output', type=pathlib.Path, help='the debian/changelog to write')
parser.add_argument('--version', help='the Debian version of the newest entry instead of its own')
args = parser.parse_args()
try:
found = entries(args.changelog.read_text(encoding='utf-8'))
control = args.control.read_text(encoding='utf-8')
if not found:
raise ValueError('no entry')
text = debian(found, control_field(control, 'Source'), control_field(control, 'Maintainer'), args.version)
except (OSError, ValueError) as error:
print(f'changelog.py: {args.changelog}: {error}', file=sys.stderr)
return 1
args.output.write_text(text, encoding='utf-8')
return 0
if __name__ == '__main__':
sys.exit(main())
+22 -20
View File
@@ -1,10 +1,11 @@
#!/usr/bin/env python3
"""Build the next numbered dev build and publish it to a test project's repository: lm-dev-build.py.
The serial N in .dev-build.serial of the repository is that of the last dev build; each build that
succeeds writes its own, one higher, and release.py writes 0 when it releases. The build's version
is the newest changelog entry's with ~devN before its Debian revision, 0.41.0-1 becoming
0.41.0~dev7-1, so the release of that entry is newer than all its dev builds. ./build.sh builds it
The serial N, the setting LXD_DEV_BUILD_SERIAL (lm_dev.setting, 0 by default), is that of the last
dev build; each build that succeeds writes its own, one higher, into .lm-dev-config/settings.json,
and release.py writes 0 there when it releases. The build's version is the Debian version of the
newest entry of CHANGELOG.md (bin/changelog.py) with ~devN before its revision, 0.41.0 (0.41.0-1)
becoming 0.41.0~dev7-1, so the release of that entry is newer than all its dev builds. ./build.py builds it
with CONTAINER_RUNTIME and DOCKER_CONTEXT from the environment; the build is moved to out/dev/,
copied into the repository container of the project --project (LXD_PROJECT, lm-dev by default)
made by lm-dev-lxd-project.py, and published there. The remote is the project's, read from
@@ -13,20 +14,19 @@ made by lm-dev-lxd-project.py, and published there. The remote is the project's,
import argparse
import json
import os
import re
import subprocess
import sys
from lm_dev import PROJECT, ROOT, config_path, lxc_exec
import changelog
from lm_dev import PROJECT, ROOT, config_path, lxc_exec, save_setting, setting
SERIAL = ROOT / '.dev-build.serial'
CHANGELOG = ROOT / 'debian-package' / 'debian' / 'changelog'
CHANGELOG = ROOT / 'CHANGELOG.md'
CONTROL = ROOT / 'debian-package' / 'debian' / 'control'
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT),
parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the test project made by lm-dev-lxd-project.py, whose remote is used (LXD_PROJECT, '
f'default {PROJECT})')
args = parser.parse_args()
@@ -35,19 +35,21 @@ def main():
sys.exit(f'no {state_file}; create the project with lm-dev-lxd-project.py create')
state = json.loads(state_file.read_text(encoding='utf-8'))
# The newest entry's first line is "package (version) distribution; urgency=...".
match = re.match(r'(\S+) \(([^)]+)\)', CHANGELOG.read_text(encoding='utf-8'))
if not match:
sys.exit(f'no version in the first line of {CHANGELOG}')
package, version = match.groups()
number = int(SERIAL.read_text(encoding='utf-8').strip()) + 1 if SERIAL.is_file() else 1
upstream, dash, revision = version.rpartition('-')
dev = f'{upstream}~dev{number}-{revision}' if dash else f'{version}~dev{number}'
try:
found = changelog.entries(CHANGELOG.read_text(encoding='utf-8'))
package = changelog.control_field(CONTROL.read_text(encoding='utf-8'), 'Source')
except ValueError as error:
sys.exit(f'{CHANGELOG}: {error}')
if not found:
sys.exit(f'{CHANGELOG} has no entry')
number = int(setting('LXD_DEV_BUILD_SERIAL', 0)) + 1
upstream, _, revision = changelog.debian_version(found[0]['version']).rpartition('-')
dev = f'{upstream}~dev{number}-{revision}'
print(f'building {package} {dev}')
if subprocess.run(['./build.sh', '--build-arg', f'DEB_VERSION={dev}'], cwd=ROOT).returncode != 0:
if subprocess.run(['./build.py', '--build-arg', f'DEB_VERSION={dev}'], cwd=ROOT).returncode != 0:
sys.exit(f'the build of {dev} failed; the serial stays {number - 1}')
SERIAL.write_text(f'{number}\n', encoding='utf-8')
save_setting('LXD_DEV_BUILD_SERIAL', number)
# The dev build leaves out/ to out/dev/, so out/ keeps the release builds.
target = ROOT / 'out' / 'dev'
+30 -22
View File
@@ -21,17 +21,20 @@ project and those files.
import argparse
import json
import os
import re
import subprocess
import sys
import time
from lm_dev import PROJECT, TESTS, VAULT_PORT, VaultError, config_path, enrol_instance, lxc_exec, vault_initialise, \
vault_state, vault_unseal
from lm_dev import PROJECT, TESTS, VAULT_PORT, MissingSetting, VaultError, config_path, enrol_instance, lxc_exec, \
setting, vault_initialise, vault_state, vault_unseal
NETWORKS = ('wan', 'lana', 'lanb')
# The settings of the options of uplink setup, which have no defaults.
UPLINK_SETTINGS = {'parent': 'LXD_UPLINK_PARENT', 'gateway': 'LXD_UPLINK_GATEWAY', 'dns': 'LXD_UPLINK_DNS',
'ovn_ranges': 'LXD_UPLINK_OVN_RANGES', 'routes': 'LXD_UPLINK_ROUTES'}
def lxc(*args, project, check=True, input=None):
"""Run lxc with the arguments in the project; raise CalledProcessError when it fails, unless check is false."""
@@ -217,10 +220,11 @@ def uplink(args):
if exists:
print(f'{args.remote} has the network {args.uplink} already')
return
missing = [option for option, value in (('--parent', args.parent), ('--gateway', args.gateway), ('--dns', args.dns),
('--ovn-ranges', args.ovn_ranges), ('--routes', args.routes)) if not value]
if missing:
sys.exit(f'uplink setup needs {", ".join(missing)}')
for option, name in UPLINK_SETTINGS.items():
try:
setattr(args, option, getattr(args, option) or setting(name))
except MissingSetting as missing:
sys.exit(f'uplink setup: --{option.replace("_", "-")} or {missing}')
lxc('network', 'create', network, '--type=physical', f'parent={args.parent}', f'ipv4.gateway={args.gateway}',
f'dns.nameservers={args.dns}', f'ipv4.ovn.ranges={args.ovn_ranges}', f'ipv4.routes={args.routes}',
project='default')
@@ -233,31 +237,33 @@ def main():
parser.add_argument('action', choices=('create', 'remove', 'vault', 'uplink'))
parser.add_argument('operation', nargs='?', choices=('setup', 'create', 'unseal', 'remove'),
help='after vault: create, unseal or remove; after uplink: setup or remove')
parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--pool', default=os.environ.get('LXD_POOL'),
parser.add_argument('--remote', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--pool',
help='the storage pool of the project, for create (LXD_POOL)')
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT),
parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the project (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'),
parser.add_argument('--image', default=setting('LXD_IMAGE', 'ubuntu:26.04'),
help='the image of the repository container (LXD_IMAGE, default ubuntu:26.04)')
parser.add_argument('--vault-address', default=os.environ.get('LXD_VAULT_ADDRESS'),
parser.add_argument('--vault-address', default=setting('LXD_VAULT_ADDRESS', None),
help="the listen address of the Vault's forward, one of the uplink's routes "
'(LXD_VAULT_ADDRESS); without it one is allocated')
parser.add_argument('--uplink', default=os.environ.get('LXD_UPLINK', 'uplink'),
parser.add_argument('--uplink', default=setting('LXD_UPLINK', 'uplink'),
help='the physical uplink network of the OVN networks (LXD_UPLINK, default uplink)')
parser.add_argument('--parent', default=os.environ.get('LXD_UPLINK_PARENT'),
parser.add_argument('--parent',
help='uplink setup: the host bridge on the LAN (LXD_UPLINK_PARENT)')
parser.add_argument('--gateway', default=os.environ.get('LXD_UPLINK_GATEWAY'),
parser.add_argument('--gateway',
help='uplink setup: the LAN gateway as address/prefix (LXD_UPLINK_GATEWAY)')
parser.add_argument('--dns', default=os.environ.get('LXD_UPLINK_DNS'),
parser.add_argument('--dns',
help='uplink setup: the LAN name servers, comma-separated (LXD_UPLINK_DNS)')
parser.add_argument('--ovn-ranges', default=os.environ.get('LXD_UPLINK_OVN_RANGES'),
parser.add_argument('--ovn-ranges',
help='uplink setup: LAN addresses for OVN routers, FIRST-LAST (LXD_UPLINK_OVN_RANGES)')
parser.add_argument('--routes', default=os.environ.get('LXD_UPLINK_ROUTES'),
parser.add_argument('--routes',
help='uplink setup: LAN subnets for network forwards, CIDR (LXD_UPLINK_ROUTES)')
args = parser.parse_args()
if not args.remote:
parser.error('--remote or LXD_REMOTE is required')
try:
args.remote = args.remote or setting('LXD_REMOTE')
except MissingSetting as missing:
parser.error(f'--remote or {missing}')
operations = {'uplink': ('setup', 'remove'), 'vault': ('create', 'unseal', 'remove')}
if args.operation not in operations.get(args.action, (None,)):
parser.error('setup or remove follows uplink, create, unseal or remove follows vault, and nothing else')
@@ -292,8 +298,10 @@ def main():
if args.action == 'remove':
sys.exit(0 if remove(args, state, key) else 1)
if not args.pool:
parser.error('--pool or LXD_POOL is required')
try:
args.pool = args.pool or setting('LXD_POOL')
except MissingSetting as missing:
parser.error(f'--pool or {missing}')
if subprocess.run(['lxc', 'project', 'show', f'{args.remote}:{args.project}'], capture_output=True).returncode == 0:
sys.exit(f'project {args.project} exists on {args.remote}; remove it first or choose another --project')
state.parent.mkdir(parents=True, exist_ok=True)
+4 -5
View File
@@ -2,22 +2,21 @@
"""Print the current TOTP code of a user of a Linux Manager VM: lm-dev-otp-code.py.
The code is the one of the key <vm>-<user> in the TOTP engine of the Vault of the project --project
(LXD_PROJECT, lm-dev by default), for --user (admin by default) of the VM --vm (lm-dev), which
(LXD_PROJECT, lm-dev by default), for --user (admin by default) of the VM --vm (router), which
lm-dev-otp-register.py or lm-dev-vm.py create enrolled.
"""
import argparse
import os
import sys
from lm_dev import PROJECT, VaultError, otp_code
from lm_dev import PROJECT, VM, VaultError, otp_code, setting
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT),
parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the project of the VM (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)')
parser.add_argument('--vm', default=VM, help=f'the name of the VM (default {VM})')
parser.add_argument('--user', default='admin', help='the user (default admin)')
args = parser.parse_args()
try:
+12 -10
View File
@@ -1,30 +1,32 @@
#!/usr/bin/env python3
"""Register a TOTP token for a user of a Linux Manager VM on an LXD remote: lm-dev-otp-register.py.
The token is enrolled for --user (admin by default) of the VM --vm (lm-dev) in the project --project
The token is enrolled for --user (admin by default) of the VM --vm (router) in the project --project
(LXD_PROJECT, lm-dev by default) on the remote --remote (LXD_REMOTE): the project's Vault generates
the key in its TOTP engine as <vm>-<user> and hands it to the VM, where linuxmanager_users stores
it with its current code, replacing a token the user had. The secret stays in the Vault and the
VM; lm-dev-otp-code.py prints the user's codes.
it with its current code, replacing a token the user had. For the administrator of
.lm-dev-config/vm-PROJECT-VM.json, the key is made from the file's otp_url when it has one, and a generated key's
otpauth URI is kept there as otp_url. lm-dev-otp-code.py prints the user's codes.
"""
import argparse
import os
import sys
from lm_dev import PROJECT, enrol_otp, totp_key
from lm_dev import PROJECT, VM, MissingSetting, enrol_otp, setting, totp_key
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT),
parser.add_argument('--remote', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the project of the VM (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)')
parser.add_argument('--vm', default=VM, help=f'the name of the VM (default {VM})')
parser.add_argument('--user', default='admin', help='the user to enrol (default admin)')
args = parser.parse_args()
if not args.remote:
parser.error('--remote or LXD_REMOTE is required')
try:
args.remote = args.remote or setting('LXD_REMOTE')
except MissingSetting as missing:
parser.error(f'--remote or {missing}')
problem = enrol_otp(args.remote, args.project, args.vm, args.user)
if problem:
sys.exit(problem)
+12 -12
View File
@@ -16,7 +16,6 @@ import argparse
import importlib
import ipaddress
import json
import os
import pathlib
import re
import secrets
@@ -24,8 +23,8 @@ import subprocess
import sys
import time
from lm_dev import HANDOVER_DIR, ROOT, TESTS, VAULT_PORT, VaultError, config_path, enrol_instance, hand_over, \
host_address, lxc_exec, newest_deb, store_secret, vault_initialise
from lm_dev import HANDOVER_DIR, ROOT, TESTS, VAULT_PORT, MissingSetting, VaultError, config_path, enrol_instance, hand_over, \
host_address, lxc_exec, newest_deb, setting, store_secret, vault_initialise
TMP = ROOT / 'tmp' / 'remote-test'
@@ -388,20 +387,21 @@ class Lab:
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('scenarios', nargs='+', metavar='scenario', help=f'{", ".join(SCENARIOS)} or all')
parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--pool', default=os.environ.get('LXD_POOL'),
parser.add_argument('--remote', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--pool',
help='the storage pool of the project (LXD_POOL)')
parser.add_argument('--project', default=os.environ.get('LXD_TEST_PROJECT', 'lm-test'),
parser.add_argument('--project', default=setting('LXD_TEST_PROJECT', 'lm-test'),
help='the project the instances live in (LXD_TEST_PROJECT, default lm-test)')
parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'),
parser.add_argument('--image', default=setting('LXD_IMAGE', 'ubuntu:26.04'),
help='the image of every instance (LXD_IMAGE, default ubuntu:26.04)')
parser.add_argument('--keep', action='store_true', help='leave the project and the networks in place')
parser.add_argument('--deb', help='the package to test (default the one built last, in out/ or out/dev/)')
args = parser.parse_args()
if not args.remote:
parser.error('--remote or LXD_REMOTE is required')
if not args.pool:
parser.error('--pool or LXD_POOL is required')
try:
args.remote = args.remote or setting('LXD_REMOTE')
args.pool = args.pool or setting('LXD_POOL')
except MissingSetting as missing:
parser.error(f'--{missing.name.removeprefix("LXD_").lower()} or {missing}')
scenarios = SCENARIOS if args.scenarios == ['all'] else args.scenarios
unknown = [name for name in scenarios if name not in SCENARIOS]
if unknown:
@@ -409,7 +409,7 @@ def main():
deb = pathlib.Path(args.deb) if args.deb else newest_deb()
if deb is None or not deb.is_file():
sys.exit(f'no package {args.deb}' if args.deb else 'no out/linux-manager_*_all.deb; run ./build.sh first')
sys.exit(f'no package {args.deb}' if args.deb else 'no out/linux-manager_*_all.deb; run ./build.py first')
if subprocess.run(['lxc', 'project', 'show', f'{args.remote}:{args.project}'], capture_output=True).returncode == 0:
sys.exit(f'project {args.project} exists on {args.remote}; remove it or choose another with --project')
+38 -29
View File
@@ -1,18 +1,19 @@
#!/usr/bin/env python3
"""Launch one Linux Manager server VM on an LXD remote to work with, or remove it: lm-dev-vm.py create|remove.
create launches the VM --vm (lm-dev by default) on the remote --remote (LXD_REMOTE) in the project
create launches the VM --vm (router by default) on the remote --remote (LXD_REMOTE) in the project
--project (LXD_PROJECT, lm-dev by default) with that project's default profile. In a test project
made by lm-dev-lxd-project.py, which .lm-dev-config/lxd-project-PROJECT.json describes, the VM gets the package
from that project's repository, as its apt source, so later dev builds reach it as updates;
elsewhere it gets --deb, or else the package built last, in out/ or out/dev/. The administrator is admin with a
generated password, set as ADMIN_USERNAME and ADMIN_PASSWORD in the repository's .env, and a TOTP
token, the key VM-admin of the project's Vault's TOTP engine, unless --no-otp is given;
lm-dev-otp-code.py prints its codes. The VM gets a configuration from tests/remote/configs/
(--config, core.json by default), whose @ETH0@ is the interface of its default route, @CIDR0@ its
network and @PSK@ a generated key. The VM gets an AppRole of its own in the project's Vault
elsewhere it gets --deb, or else the package built last, in out/ or out/dev/. The administrator is admin with the
password of .lm-dev-config/vm-PROJECT-VM.json, and a TOTP token, the key VM-admin of the project's Vault's TOTP
engine made from the file's otp_url, unless --no-otp is given; lm-dev-otp-code.py prints its codes. A password or
otp_url the file lacks, or all of them when there is no file, is generated and kept in the file, so a VM made again
has the same password and token until they are deleted from the file.
The VM gets a configuration from tests/remote/configs/ (--config, core.json by default), whose @ETH0@ is the
interface of its default route, @CIDR0@ its network and @PSK@ a generated key. The VM gets an AppRole of its own in the project's Vault
(lm_dev.enrol_instance), with which it reads the debconf preseed with the admin's password and the
configuration with its key, kept there as VM/preseed and VM/config, and creates its TOTP key; no
configuration with its key, kept there as VM/preseed and VM/config, and its TOTP key, generated or from otp_url; no
secret is an argument or on standard input, so create needs a project with a Vault
(lm-dev-lxd-project.py vault create). The admin's password is also kept there as VM/admin.
@@ -21,14 +22,14 @@ the same ports of the VM, and port 2222 to its SSH port. In a test project the l
network forward's on the project's WAN, --forward-address (LXD_FORWARD_ADDRESS) or else one allocated
from its uplink's routes; elsewhere NAT proxy
devices listen on the host address --listen (LXD_LISTEN, by default the IPv4 address of the host of
the remote's URL). remove deletes the VM, its forward and what the Vault keeps for it; .env is left
as it is.
the remote's URL). remove deletes the VM, its forward and what the Vault keeps
for it, and keeps .lm-dev-config/vm-PROJECT-VM.json. The defaults of the options come from the environment, else from
.lm-dev-config/settings.json (lm_dev.setting).
"""
import argparse
import ipaddress
import json
import os
import pathlib
import re
import secrets
@@ -36,8 +37,9 @@ import subprocess
import sys
import time
from lm_dev import HANDOVER_DIR, PROJECT, ROOT, TESTS, VAULT_MOUNT, VaultError, config_path, enrol_instance, enrol_otp, \
forget_instance, hand_over, host_address, lxc_exec, newest_deb, set_dotenv, store_secret, vault_state
from lm_dev import HANDOVER_DIR, PROJECT, VM, ROOT, TESTS, VAULT_MOUNT, MissingSetting, VaultError, config_path, \
credentials_path, enrol_instance, enrol_otp, forget_instance, hand_over, host_address, lxc_exec, newest_deb, \
setting, store_secret, vault_state, write_private
# The listen port and the VM port of each forward or proxy: the Manager, the status web service and SSH.
PORTS = ((7080, 7080), (7081, 7081), (2222, 22))
@@ -46,26 +48,28 @@ PORTS = ((7080, 7080), (7081, 7081), (2222, 22))
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('action', choices=('create', 'remove'))
parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT),
parser.add_argument('--remote', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the project of the VM (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)')
parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'),
parser.add_argument('--vm', default=VM, help=f'the name of the VM (default {VM})')
parser.add_argument('--image', default=setting('LXD_IMAGE', 'ubuntu:26.04'),
help='the image of the VM (LXD_IMAGE, default ubuntu:26.04)')
parser.add_argument('--config', default='core.json',
help='the configuration from tests/remote/configs/ (default core.json)')
parser.add_argument('--listen', default=os.environ.get('LXD_LISTEN'),
parser.add_argument('--listen', default=setting('LXD_LISTEN', None),
help="outside a test project, the LXD host address the proxies listen on (LXD_LISTEN, "
"default the IPv4 address of the remote URL's host)")
parser.add_argument('--forward-address', default=os.environ.get('LXD_FORWARD_ADDRESS'),
parser.add_argument('--forward-address', default=setting('LXD_FORWARD_ADDRESS', None),
help="with create in a test project, the forward's listen address, one of the uplink's routes "
"(LXD_FORWARD_ADDRESS); without it one is allocated")
parser.add_argument('--no-otp', action='store_true', help='with create, enrol no TOTP token for admin')
parser.add_argument('--deb', help='outside a test project, the package to install (default the one built last, '
'in out/ or out/dev/)')
args = parser.parse_args()
if not args.remote:
parser.error('--remote or LXD_REMOTE is required')
try:
args.remote = args.remote or setting('LXD_REMOTE')
except MissingSetting as missing:
parser.error(f'--remote or {missing}')
project_file = config_path(f'lxd-project-{args.project}.json')
project = json.loads(project_file.read_text(encoding='utf-8')) if project_file.is_file() else None
if project and project['remote'] != args.remote:
@@ -74,8 +78,10 @@ def main():
# The default listen address is the IPv4 address of the remote's host in its lxc URL.
args.listen = host_address(args.remote)
if not args.listen:
parser.error(f'no IPv4 address of the host of remote {args.remote}; give --listen or LXD_LISTEN')
parser.error(f'no IPv4 address of the host of remote {args.remote}; give --listen or LXD_LISTEN, in the '
'environment or .lm-dev-config/settings.json')
where = f'{args.remote}:{args.vm} (project {args.project})'
credentials = credentials_path(args.project, args.vm)
exists = subprocess.run(['lxc', 'info', f'{args.remote}:{args.vm}', '--project', args.project],
capture_output=True).returncode == 0
@@ -106,7 +112,7 @@ def main():
forget_instance(vault, args.vm)
except VaultError as error:
print(f'the Vault keeps what it had for {args.vm}: {error}', file=sys.stderr)
print(f'removed {where}')
print(f'removed {where}; {credentials} is kept for the next create')
return
if exists:
@@ -116,15 +122,18 @@ def main():
parser.error(f'no tests/remote/configs/{args.config}')
deb = pathlib.Path(args.deb) if args.deb else newest_deb()
if not project and (deb is None or not deb.is_file()):
sys.exit(f'no package {args.deb}' if args.deb else 'no out/linux-manager_*_all.deb; run ./build.sh first')
sys.exit(f'no package {args.deb}' if args.deb else 'no out/linux-manager_*_all.deb; run ./build.py first')
source = f'the repository {project["repository"]}' if project else str(deb)
vault = vault_state(args.project)
if vault is None:
sys.exit(f'project {args.project} has no Vault, which the secrets reach the VM through; make it with '
'lm-dev-lxd-project.py vault create')
password, psk = secrets.token_hex(16), secrets.token_hex(24)
set_dotenv({'ADMIN_USERNAME': 'admin', 'ADMIN_PASSWORD': password})
# The password and otp_url of the credentials file are reused; a missing one is generated.
known = json.loads(credentials.read_text(encoding='utf-8')) if credentials.is_file() else {}
password, psk = known.get('password') or secrets.token_hex(16), secrets.token_hex(24)
known.update(username='admin', password=password)
write_private(credentials, json.dumps(known, indent=2) + '\n')
reached = f'a forward on {project["networks"][0]}' if project else f'proxies on {args.listen}'
print(f'launching {where} from {args.image} with {source}; reached through {reached}')
@@ -234,10 +243,10 @@ def main():
sys.exit(f'{args.vm} is up, but {problem}')
print(f'{args.vm} is up at {interface.ip} with {args.config}')
print(f'administrator: admin, password in {ROOT / ".env"} (ADMIN_PASSWORD) and the Vault ({VAULT_MOUNT}/'
f'{args.vm}/admin)')
print(f'administrator: admin, password in {credentials} and the Vault ({VAULT_MOUNT}/{args.vm}/admin)')
if not args.no_otp:
print(f'administrator TOTP codes: bin/lm-dev-otp-code.py --project {args.project} --vm {args.vm}')
print(f'administrator TOTP: otp_url in {credentials}; codes: bin/lm-dev-otp-code.py --project {args.project} '
f'--vm {args.vm}')
print(f'manager: http://{args.listen}:7080/ status: http://{args.listen}:7081/ ssh: {args.listen} port 2222')
print(f'shell: lxc exec {args.remote}:{args.vm} --project {args.project} -- su -l')
print(f'remove: {sys.argv[0]} remove --remote {args.remote} --project {args.project} --vm {args.vm}')
+78 -17
View File
@@ -1,5 +1,5 @@
"""What the lm-dev scripts share: the repository's paths, lxc in an instance, the .env of the repository, the
persistent state in .lm-dev-config, the Vault of a test project, the AppRole of each instance in it, the hand-over of
"""What the lm-dev scripts share: the repository's paths, lxc in an instance, the persistent state and settings in
.lm-dev-config, the Vault of a test project, the AppRole of each instance in it, the hand-over of
secrets to an instance through it, and the TOTP tokens of the users of a VM, kept in the Vault's TOTP engine.
A secret never reaches an instance as a command-line argument or on standard input. Each instance has an AppRole of
@@ -25,8 +25,12 @@ ROOT = pathlib.Path(__file__).resolve().parent.parent
TESTS = ROOT / 'tests' / 'remote'
# The project of the manual tests, which lm-dev-lxd-project.py makes.
PROJECT = 'lm-dev'
# The state of the scripts that outlives a clean-up of tmp/: project and Vault states, keys and secrets; 0700.
# The default VM of the manual tests, which lm-dev-vm.py makes.
VM = 'router'
# The state of the scripts that outlives a clean-up of tmp/: settings, project and Vault states, keys and secrets; 0700.
CONFIG = ROOT / '.lm-dev-config'
# The settings of the scripts, the defaults of their options: a JSON object of LXD_* names and their values.
SETTINGS = CONFIG / 'settings.json'
# The Vault: its port, the KV v2 and TOTP mounts, the lifetimes of a wrapping token and of an instance's token.
VAULT_PORT = 8200
@@ -66,15 +70,42 @@ def lxc_push(remote, project, instance, source, path, mode):
'--project', project], capture_output=True, text=True).returncode == 0
def set_dotenv(values):
"""Set the variables in the repository's .env, readable by its owner only, keeping its other lines."""
dotenv = ROOT / '.env'
lines = dotenv.read_text(encoding='utf-8').splitlines() if dotenv.is_file() else []
kept = [line for line in lines if line.split('=', 1)[0] not in values]
dotenv.touch(mode=0o600)
dotenv.chmod(0o600)
dotenv.write_text(''.join(f'{line}\n' for line in kept + [f'{key}={value}' for key, value in values.items()]),
encoding='utf-8')
class MissingSetting(Exception):
"""A setting without a default that neither the environment nor SETTINGS has; name is the setting."""
def __init__(self, name):
super().__init__(f'{name}, in the environment or {SETTINGS.relative_to(ROOT)}, is required')
self.name = name
# The default of a setting that has none.
REQUIRED = object()
def setting(name, default=REQUIRED):
"""The value of the setting name, such as LXD_REMOTE: the environment's, else that of SETTINGS, else default;
MissingSetting without a default."""
if name in os.environ:
return os.environ[name]
try:
values = json.loads(SETTINGS.read_text(encoding='utf-8'))
except FileNotFoundError:
values = {}
except ValueError as error:
raise SystemExit(f'{SETTINGS} is not JSON: {error}')
if name in values:
return values[name]
if default is REQUIRED:
raise MissingSetting(name)
return default
def save_setting(name, value):
"""Set the setting name to the value in SETTINGS, keeping its other settings."""
path = config_path(SETTINGS.name)
values = json.loads(path.read_text(encoding='utf-8')) if path.is_file() else {}
values[name] = value
write_private(path, json.dumps(values, indent=2) + '\n')
def newest_deb():
@@ -250,16 +281,24 @@ def hand_over(remote, project, instance, state, name, content, destination, mode
return None
def credentials_path(project, instance):
"""The file of the administrator of the VM lm-dev-vm.py made, JSON of username, password and otp_url; 0600."""
return config_path(f'vm-{project}-{instance}.json')
def totp_key(instance, user):
"""The name of the TOTP key of the user of the instance in the Vault's TOTP engine."""
return f'{instance}-{user}'
def enrol_otp(remote, project, instance, user):
"""Enrol a new TOTP token for the user of the VM, replacing one the user had; the problem, or None.
"""Enrol a TOTP token for the user of the VM, replacing one the user had; the problem, or None.
The VM has the Vault generate the key with its AppRole and enrols its secret with its current code; the secret is
held by the Vault and the VM only, and the codes are read from the Vault (otp_code).
When the user is the administrator of the VM's credentials_path and the file has otp_url, the Vault's key is made
from that otpauth URI and the VM receives it through the Vault (hand_over), so the token stays the same. Otherwise
the VM has the Vault generate a new key with its AppRole, and for the administrator the key's otpauth URI, read
from the VM's file before it is removed, is kept in the file as otp_url, to add the token to an authenticator. The
VM enrols the key's secret with its current code; the codes are read from the Vault (otp_code).
"""
state = vault_state(project)
if state is None:
@@ -270,11 +309,33 @@ def enrol_otp(remote, project, instance, user):
except VaultError as error:
return f'the TOTP key {key} cannot be replaced: {error}'
target = f'{HANDOVER_DIR}/otp-url'
for command in (('install', '-d', '-m', '0700', HANDOVER_DIR), (HELPER, 'totp', key, instance, user, target, '0600'),
('python3', '-c', OTP_ENROL, user, target)):
credentials = credentials_path(project, instance)
known = json.loads(credentials.read_text(encoding='utf-8')) if credentials.is_file() else {}
keep = known.get('username') == user
reuse = known.get('otp_url') if keep else None
prepared = lxc_exec(remote, project, instance, 'install', '-d', '-m', '0700', HANDOVER_DIR)
if prepared.returncode != 0:
return f'{HANDOVER_DIR} cannot be made in {instance}: {prepared.stderr.strip()}'
if reuse:
try:
vault_call(state['url'], 'POST', f'/v1/{TOTP_MOUNT}/keys/{key}', {'url': reuse},
token=state['root_token'])
except VaultError as error:
return f'the TOTP key {key} cannot be made from otp_url: {error}'
problem = hand_over(remote, project, instance, state, 'otp-url', reuse + '\n', target, '0600')
if problem:
return problem
steps = ()
else:
steps = ((HELPER, 'totp', key, instance, user, target, '0600'), *((('cat', target),) if keep else ()))
for command in (*steps, ('python3', '-c', OTP_ENROL, user, target)):
result = lxc_exec(remote, project, instance, *command)
if result.returncode != 0:
return f'{user} was not enrolled: {(result.stderr.strip().splitlines() or ["lxc exec failed"])[-1]}'
if command[0] == 'cat':
known['otp_url'] = result.stdout.strip()
if keep:
write_private(credentials, json.dumps(known, indent=2) + '\n')
return None
Executable
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env python3
"""Build the package in a container and write it to out/: build.py [CONTAINER BUILD OPTIONS].
The Dockerfile builds the Manager's application and the package, whose debian/changelog it writes
from CHANGELOG.md; the build's files are then streamed out of the image as a tar archive into out/,
so no bind mount is needed. The container runtime is CONTAINER_RUNTIME from the environment, for
example docker with DOCKER_CONTEXT naming a remote engine, else Apple's container CLI on macOS and
Docker on Linux. Options are passed to the runtime's build, such as --build-arg DEB_VERSION=V. A
failure is a message on standard error and a non-zero exit status.
"""
import os
import pathlib
import platform
import subprocess
import sys
import tarfile
ROOT = pathlib.Path(__file__).resolve().parent
OUT = ROOT / 'out'
IMAGE = 'linux-manager-builder'
#: The container runtime of each platform when CONTAINER_RUNTIME is not set.
RUNTIMES = {'Darwin': 'container', 'Linux': 'docker'}
def main():
runtime = os.environ.get('CONTAINER_RUNTIME') or RUNTIMES.get(platform.system())
if not runtime:
sys.exit(f'build.py: unsupported platform {platform.system()}; set CONTAINER_RUNTIME')
OUT.mkdir(exist_ok=True)
build = [runtime, 'build', '--build-arg', f'HOST_UID={os.getuid()}', '--build-arg', f'HOST_GID={os.getgid()}',
'-t', IMAGE, *sys.argv[1:], '.']
if subprocess.run(build, cwd=ROOT).returncode != 0:
sys.exit('build.py: the image build failed')
with subprocess.Popen([runtime, 'run', '--rm', IMAGE, 'tar', '-cf', '-', '-C', '/out', '.'], cwd=ROOT,
stdout=subprocess.PIPE) as stream:
with tarfile.open(fileobj=stream.stdout, mode='r|') as archive:
archive.extractall(OUT, filter='data')
if stream.returncode != 0:
sys.exit('build.py: the build files could not be copied out of the image')
print(f'Build artifacts written to {OUT.relative_to(ROOT)}/')
return 0
if __name__ == '__main__':
sys.exit(main())
-20
View File
@@ -1,20 +0,0 @@
#!/bin/sh
set -e
# CONTAINER_RUNTIME from the environment, for example docker with DOCKER_CONTEXT naming a remote engine;
# otherwise Apple container CLI on macOS and Docker CE on Linux.
if [ -z "${CONTAINER_RUNTIME:-}" ]; then
case "$(uname -s)" in
Darwin) CONTAINER_RUNTIME=container ;;
Linux) CONTAINER_RUNTIME=docker ;;
*) printf 'ERROR: unsupported platform %s\n' "$(uname -s)" >&2; exit 1 ;;
esac
fi
mkdir -p out
$CONTAINER_RUNTIME build --build-arg HOST_UID=$(id -u) --build-arg HOST_GID=$(id -g) -t linux-manager-builder "$@" .
# Artifacts are streamed out as a tar archive, so no bind mount is needed.
$CONTAINER_RUNTIME run --rm linux-manager-builder tar -cf - -C /out . | tar -xf - -C out
echo "Build artifacts written to out/"
File diff suppressed because it is too large. Load diff
+1
View File
@@ -41,6 +41,7 @@ src/usr/lib/linux-manager/upgrade usr/lib/linux-manager/
src/usr/lib/linux-manager/linuxmanager_platforms/*.py usr/lib/linux-manager/linuxmanager_platforms/
src/usr/share/linux-manager/templates/* usr/share/linux-manager/templates/
src/usr/share/linux-manager/sql/* usr/share/linux-manager/sql/
src/usr/share/linux-manager/schema/* usr/share/linux-manager/schema/
src/usr/share/bash-completion/completions/*.bash usr/share/bash-completion/completions/
src/usr/lib/systemd/system/caddy.service.d/linux-manager.conf usr/lib/systemd/system/caddy.service.d/
src/usr/share/doc/linux-manager/linux-manager.json.example usr/share/doc/linux-manager/
@@ -17,7 +17,9 @@ CONSOLE_UID_MIN and the gidNumber of the local group CONSOLE_GROUP; nslcd serves
linuxManagerConsoleLogin TRUE to the system over the local socket.
ou=pki holds the server's PKI (linuxmanager_pki): an entry per CA, and under it an entry per
certificate the CA issued. Private keys are readable by root alone, the database's root DN.
certificate the CA issued. Private keys are readable by root, the database's root DN, and by the
members of the group PKI_GROUP, which also write ou=pki: an application that keeps its CAs there,
such as Simple CA, binds as a service account in that group.
ou=roles holds the roles of the resources of the OpenID Provider: an entry per role,
cn=<resource>:<role>, whose members are the groups, users and service accounts it is assigned to.
@@ -32,6 +34,7 @@ import secrets
import ldap
import ldap.modlist
import ldap.sasl
import ldif
URI = 'ldapi:///'
#: The local socket ldapi:/// names, which slapd listens on.
@@ -64,102 +67,15 @@ LOCKOUT_SECONDS = 900
#: The overlays of the database, in the order they are configured.
OVERLAYS = ('ppolicy', 'otp')
#: The package's own schema, under the LDAP arc of the Linux Manager OID arc (OID-REGISTRY.txt):
#: attribute types under .1 and object classes under .2. linuxManagerAccount, auxiliary, adds properties of the
#: package to a user of either kind: mail, for a Manager-only account, linuxManagerScope,
#: authorization scopes, of which service marks a service account, displayName and
#: description, the labels of a service account, and linuxManagerConsoleLogin and
#: linuxManagerConsoleAccount, whether the user may use a console and the local account it runs as,
#: without which it runs as the user's own posixAccount, and linuxManagerWireGuardPeer, each a
#: WireGuard peer of the user as "<public key> <IP>[,<IP>...]", and linuxManagerPasskey, each a
#: passkey of the user as JSON (linuxmanager_passkeys). A service account with linuxManagerRedirectUri
#: is a client of the OpenID Provider (linuxmanager_oidc): the URIs it is sent back to after a sign-in
#: and, linuxManagerPostLogoutRedirectUri, after a sign-out, and linuxManagerAllowedGroup, the DNs of the
#: groups whose members may sign in to it; linuxManagerGrantType, the further grants it may use,
#: linuxManagerPublicClient, whether it has no secret, and linuxManagerClientScope, the scopes of
#: resources it may ask for, as <resource>:<scope>. A service account with linuxManagerResourceScope
#: is a resource of the OpenID Provider with those scopes. linuxManagerRole is a role of a resource,
#: named cn=<resource>:<role>, with the DNs of the groups and accounts it is assigned to in
#: member. linuxManagerAuthority is a CA of the PKI: its
#: certificate and CRL (cACertificate and certificateRevocationList of RFC 4523), its key, the
#: CSR it waits with for its certificate, the number of its last CRL, where the CRL came from,
#: and when it was retired; the root also holds the Simple CA token, linuxManagerToken, and the
#: name of the Simple CA issuing CA that signs with it, linuxManagerUpstreamName.
#: linuxManagerHostCertificate, cn=https, is the server's HTTPS certificate when no ACME CA or
#: issuing CA gives it: the certificate with its chain, its key, the CSR waiting for a certificate
#: of another CA and that CSR's key, and its kind, self-signed or external. linuxManagerCertificate is a certificate a CA issued, named by its
#: serial number: the certificate, the key the server keeps for its own and the users'
#: certificates, its kind, template, names and expiry, and its revocation.
SCHEMA_OID = '1.3.6.1.4.1.67380.10.1.2'
SCHEMA_NAME = 'linux-manager'
_STRING = 'EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} SINGLE-VALUE'
_TIME = 'EQUALITY generalizedTimeMatch ORDERING generalizedTimeOrderingMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE'
_OCTETS = 'EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 SINGLE-VALUE'
SCHEMA_ATTRIBUTE_TYPES = (
f"( {SCHEMA_OID}.1.1 NAME 'linuxManagerScope' DESC 'Linux Manager: an authorization scope of the account' "
"EQUALITY caseIgnoreMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} )",
f"( {SCHEMA_OID}.1.2 NAME 'linuxManagerPrivateKey' DESC 'Linux Manager: a private key, PEM' {_OCTETS} )",
f"( {SCHEMA_OID}.1.3 NAME 'linuxManagerCertificateRequest' DESC 'Linux Manager: the CSR of a CA, PEM' {_OCTETS} )",
f"( {SCHEMA_OID}.1.4 NAME 'linuxManagerCRLNumber' DESC 'Linux Manager: the number of the last CRL of a CA' "
"EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )",
f"( {SCHEMA_OID}.1.5 NAME 'linuxManagerCRLSource' DESC 'Linux Manager: signed or uploaded, where the CRL of a CA came from' {_STRING} )",
f"( {SCHEMA_OID}.1.6 NAME 'linuxManagerRetired' DESC 'Linux Manager: when a CA was retired' {_TIME} )",
f"( {SCHEMA_OID}.1.7 NAME 'linuxManagerKind' DESC 'Linux Manager: ca, router, user or external, the kind of a certificate' {_STRING} )",
f"( {SCHEMA_OID}.1.8 NAME 'linuxManagerTemplate' DESC 'Linux Manager: the template of a certificate' {_STRING} )",
f"( {SCHEMA_OID}.1.9 NAME 'linuxManagerSubjectAltName' DESC 'Linux Manager: a subject alternative name of a certificate' "
"EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} )",
f"( {SCHEMA_OID}.1.10 NAME 'linuxManagerNotAfter' DESC 'Linux Manager: when a certificate expires' {_TIME} )",
f"( {SCHEMA_OID}.1.11 NAME 'linuxManagerRevoked' DESC 'Linux Manager: when a certificate was revoked' {_TIME} )",
f"( {SCHEMA_OID}.1.12 NAME 'linuxManagerRevocationReason' DESC 'Linux Manager: why a certificate was revoked' {_STRING} )",
f"( {SCHEMA_OID}.1.13 NAME 'linuxManagerConsoleLogin' DESC 'Linux Manager: whether the user may use a console' "
"EQUALITY booleanMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.7 SINGLE-VALUE )",
f"( {SCHEMA_OID}.1.14 NAME 'linuxManagerConsoleAccount' DESC 'Linux Manager: the local account the console of the user runs as' "
f"{_STRING} )",
f"( {SCHEMA_OID}.1.15 NAME 'linuxManagerWireGuardPeer' DESC 'Linux Manager: a WireGuard peer of the user, its public key and IPs' "
"EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )",
f"( {SCHEMA_OID}.1.16 NAME 'linuxManagerPasskey' DESC 'Linux Manager: a passkey of the user, its credential as JSON' "
"EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{4096} )",
f"( {SCHEMA_OID}.1.17 NAME 'linuxManagerRedirectUri' DESC 'Linux Manager: a redirect URI of an OpenID Connect client' "
"EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )",
f"( {SCHEMA_OID}.1.18 NAME 'linuxManagerPostLogoutRedirectUri' DESC 'Linux Manager: a post-logout redirect URI of an "
"OpenID Connect client' EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )",
f"( {SCHEMA_OID}.1.19 NAME 'linuxManagerAllowedGroup' DESC 'Linux Manager: a group whose members may sign in to an "
"OpenID Connect client' EQUALITY distinguishedNameMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 )",
f"( {SCHEMA_OID}.1.20 NAME 'linuxManagerGrantType' DESC 'Linux Manager: a grant an OpenID Connect client may use besides "
"the authorization code' EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{64} )",
f"( {SCHEMA_OID}.1.21 NAME 'linuxManagerPublicClient' DESC 'Linux Manager: whether an OpenID Connect client has no secret' "
"EQUALITY booleanMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.7 SINGLE-VALUE )",
f"( {SCHEMA_OID}.1.22 NAME 'linuxManagerClientScope' DESC 'Linux Manager: a scope of a resource an OpenID Connect client "
"may ask for' EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{128} )",
f"( {SCHEMA_OID}.1.23 NAME 'linuxManagerResourceScope' DESC 'Linux Manager: a scope of a resource of the OpenID Provider' "
"EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{64} )",
f"( {SCHEMA_OID}.1.24 NAME 'linuxManagerToken' DESC 'Linux Manager: the Simple CA token that signs the issuing CAs' "
f"{_OCTETS} )",
f"( {SCHEMA_OID}.1.25 NAME 'linuxManagerUpstreamName' DESC 'Linux Manager: the Simple CA issuing CA of the token' "
f"{_STRING} )",
f"( {SCHEMA_OID}.1.26 NAME 'linuxManagerCertificateChain' DESC 'Linux Manager: a certificate and its chain, PEM' "
f"{_OCTETS} )",
f"( {SCHEMA_OID}.1.27 NAME 'linuxManagerRequestKey' DESC 'Linux Manager: the private key of a CSR, PEM' {_OCTETS} )",
)
SCHEMA_OBJECT_CLASSES = (
f"( {SCHEMA_OID}.2.1 NAME 'linuxManagerAccount' DESC 'Linux Manager: properties of a user or a Manager-only account' "
"SUP top AUXILIARY MAY ( mail $ linuxManagerScope $ displayName $ description $ linuxManagerConsoleLogin $ "
"linuxManagerConsoleAccount $ linuxManagerWireGuardPeer $ linuxManagerPasskey $ linuxManagerRedirectUri $ "
"linuxManagerPostLogoutRedirectUri $ linuxManagerAllowedGroup $ linuxManagerGrantType $ linuxManagerPublicClient $ "
"linuxManagerClientScope $ linuxManagerResourceScope ) )",
f"( {SCHEMA_OID}.2.2 NAME 'linuxManagerAuthority' DESC 'Linux Manager: a CA of the PKI' SUP top STRUCTURAL MUST cn "
"MAY ( cACertificate $ certificateRevocationList $ linuxManagerPrivateKey $ linuxManagerCertificateRequest $ "
"linuxManagerCRLNumber $ linuxManagerCRLSource $ linuxManagerRetired $ linuxManagerToken $ "
"linuxManagerUpstreamName ) )",
f"( {SCHEMA_OID}.2.3 NAME 'linuxManagerCertificate' DESC 'Linux Manager: a certificate a CA of the PKI issued' SUP top "
"STRUCTURAL MUST serialNumber MAY ( cn $ userCertificate $ linuxManagerPrivateKey $ linuxManagerKind $ linuxManagerTemplate $ "
"linuxManagerSubjectAltName $ linuxManagerNotAfter $ linuxManagerRevoked $ linuxManagerRevocationReason ) )",
f"( {SCHEMA_OID}.2.4 NAME 'linuxManagerRole' DESC 'Linux Manager: a role of a resource of the OpenID Provider' SUP top "
"STRUCTURAL MUST cn MAY ( description $ member ) )",
f"( {SCHEMA_OID}.2.5 NAME 'linuxManagerHostCertificate' DESC 'Linux Manager: a certificate of the server kept with "
"its key' SUP top STRUCTURAL MUST cn MAY ( linuxManagerCertificateChain $ linuxManagerPrivateKey $ "
"linuxManagerCertificateRequest $ linuxManagerRequestKey $ linuxManagerKind ) )",
)
#: The package's schema, two schema entries of cn=config, each loaded from its LDIF file (ldapadd's form): the PKI,
#: linux-manager-pki, which a slapd without the package loads alike, and the accounts, the clients and resources of
#: the OpenID Provider and their roles, linux-manager. The files describe their attribute types and object classes.
SCHEMA_DIR = pathlib.Path('/usr/share/linux-manager/schema')
SCHEMA_FILES = (SCHEMA_DIR / 'linux-manager-pki.ldif', SCHEMA_DIR / 'linux-manager.ldif')
#: The group whose members manage the PKI, ou=pki with the keys; it is made when its first member is added.
PKI_GROUP = 'pki-managers'
PKI_MANAGERS = f'cn={PKI_GROUP},{GROUPS}'
#: The TOTP parameters: digits, the OID of HMAC-SHA1, seconds per time step, and the time steps accepted before and after now.
TOTP_DIGITS = 6
@@ -171,7 +87,7 @@ TOTP_WINDOW = 1
DISABLED = '000001010000Z'
#: The indexes of the database.
INDEXES = ('objectClass eq', 'uid eq', 'uidNumber eq', 'linuxManagerConsoleLogin eq')
INDEXES = ('objectClass eq', 'uid eq', 'uidNumber eq', 'linuxManagerConsoleLogin eq', 'linuxManagerCertificateName eq')
#: The POSIX accounts of console login (linuxmanager_users.console): the lowest uidNumber, which nslcd's nss_min_uid
#: matches, the local group that is their primary group and grants sudo, the shell and the parent of their homes.
@@ -182,12 +98,14 @@ CONSOLE_HOMES = '/home'
#: The ACLs of the database, in order.
ACCESS = (
'to attrs=linuxManagerPrivateKey,linuxManagerToken,linuxManagerRequestKey by * none',
f'to attrs=linuxManagerPrivateKey,linuxManagerToken,linuxManagerRequestKey by group.exact="{PKI_MANAGERS}" manage '
'by * none',
f'to attrs=userPassword by dn.exact="{MANAGER}" =wx by self =wx by anonymous auth by * none',
f'to attrs=oathSecret by dn.exact="{MANAGER}" =w by * none',
f'to dn.subtree="{USERS}" by dn.exact="{MANAGER}" manage by * read',
f'to dn.subtree="{GROUPS}" by dn.exact="{MANAGER}" manage by * read',
f'to dn.subtree="{ROLES}" by dn.exact="{MANAGER}" manage by * read',
f'to dn.subtree="{PKI}" by group.exact="{PKI_MANAGERS}" manage by * read',
'to * by * read',
)
@@ -236,27 +154,32 @@ def _ensure_modules(connection):
def _ensure_schema(connection):
"""Add the package's schema to cn=config when missing, else add the definitions it lacks; a definition that differs
from the one of the same OID replaces the whole list of its kind."""
found = connection.search_s('cn=schema,cn=config', ldap.SCOPE_ONELEVEL, f'(cn=*{SCHEMA_NAME})',
['olcAttributeTypes', 'olcObjectClasses'])
attributes = {'olcAttributeTypes': list(SCHEMA_ATTRIBUTE_TYPES), 'olcObjectClasses': list(SCHEMA_OBJECT_CLASSES)}
if not found:
connection.add_s(f'cn={SCHEMA_NAME},cn=schema,cn=config', ldap.modlist.addModlist(
dict({name: [value.encode() for value in values] for name, values in attributes.items()},
objectClass=[b'olcSchemaConfig'], cn=[SCHEMA_NAME.encode()])))
return
dn, current = found[0]
for name, wanted in attributes.items():
present = unordered(current.get(name, []))
oids = {value.split()[1] for value in present}
missing = [value for value in wanted if value not in present]
if not missing:
"""Add each schema of SCHEMA_FILES to cn=config when missing, else add the definitions it lacks; a definition that
differs from the one of the same OID replaces the whole list of its kind."""
for path in SCHEMA_FILES:
with open(path, encoding='utf-8') as handle:
records = ldif.LDIFRecordList(handle)
records.parse()
dn, wanted = records.all_records[0]
name = wanted['cn'][0]
found = [(found_dn, current) for found_dn, current in connection.search_s(
'cn=schema,cn=config', ldap.SCOPE_ONELEVEL, f'(cn=*{name.decode()})', ['cn', 'olcAttributeTypes', 'olcObjectClasses'])
if ORDER.sub(b'', current['cn'][0]) == name]
if not found:
connection.add_s(dn, ldap.modlist.addModlist(wanted))
continue
if any(value.split()[1] in oids for value in missing):
connection.modify_s(dn, [(ldap.MOD_REPLACE, name, [value.encode() for value in wanted])])
else:
connection.modify_s(dn, [(ldap.MOD_ADD, name, [value.encode() for value in missing])])
found_dn, current = found[0]
for kind in ('olcAttributeTypes', 'olcObjectClasses'):
values = [value.decode() for value in wanted.get(kind, [])]
present = unordered(current.get(kind, []))
oids = {value.split()[1] for value in present}
missing = [value for value in values if value not in present]
if not missing:
continue
if any(value.split()[1] in oids for value in missing):
connection.modify_s(found_dn, [(ldap.MOD_REPLACE, kind, [value.encode() for value in values])])
else:
connection.modify_s(found_dn, [(ldap.MOD_ADD, kind, [value.encode() for value in missing])])
def _ensure_password_hash(connection):
@@ -3,7 +3,7 @@
The settings file (CONFIG_FILE unless another is given) sets, all optional: router_url, database,
listen, bind, port, terraform_dir and iac_tool. bind is the one address to listen on. Without
router_url, terraform_dir names the Terraform root module whose output router_web_url gives the
URL of the server's web service, read with iac_tool, terraform (the default) or tofu; dev.sh uses
URL of the server's web service, read with iac_tool, terraform (the default) or tofu; dev.py uses
it to run the manager on a workstation. On the server, where ROUTER_CONFIG_FILE is, the manager
listens without bind on linuxmanager_net.MANAGER_LOOPBACK_PORT of the loopback address, where
Caddy calls it: Caddy serves port over plain HTTP and https.manager_port over HTTPS, and the
@@ -33,7 +33,9 @@ optional description and at least one member; a group cannot be empty, so the la
cannot leave it and a user who is the last member of a group cannot be removed. ADMIN_GROUP grants the management of
the server, the allowed groups of the OpenID Provider's clients who may sign in to them, and the editors group of a web
site who may change its files (linuxmanager_sites); renaming a group renames it in those, and a group a client allows or a
site has cannot be removed.
site has cannot be removed. The members of linuxmanager_ldap.PKI_GROUP manage the PKI in ou=pki with its keys,
which an application that keeps its CAs there binds for as a service account; the group is made with its first member,
and renaming it takes that access away.
A VPN user may have WireGuard peers, each a device with its public key and its IPs, in
linuxManagerWireGuardPeer; linux-manager-setup writes a [Peer] of wg0.conf for each peer of a user who
@@ -0,0 +1,90 @@
# Linux Manager's PKI schema: CAs, the certificates they issued and the server's host certificates,
# with their keys. It needs only the core schema. A slapd without Linux Manager loads it with:
#
# ldapadd -Y EXTERNAL -H ldapi:/// -f linux-manager-pki.ldif
#
# OIDs: the LDAP arc 1.3.6.1.4.1.67380.10.1.2 of OID-REGISTRY.txt, attribute types under .1 and
# object classes under .2.
dn: cn=linux-manager-pki,cn=schema,cn=config
objectClass: olcSchemaConfig
cn: linux-manager-pki
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.2 NAME
'linuxManagerPrivateKey' DESC 'Linux Manager: a private key, PEM' EQUALITY
octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.3 NAME
'linuxManagerCertificateRequest' DESC 'Linux Manager: the CSR of a CA, PEM'
EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 SINGLE-VALUE
)
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.4 NAME 'linuxManagerCRLNumber'
DESC 'Linux Manager: the number of the last CRL of a CA' EQUALITY
integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.5 NAME 'linuxManagerCRLSource'
DESC 'Linux Manager: signed or uploaded, where the CRL of a CA came from'
EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256}
SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.6 NAME 'linuxManagerRetired'
DESC 'Linux Manager: when a CA was retired' EQUALITY generalizedTimeMatch
ORDERING generalizedTimeOrderingMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.24
SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.7 NAME 'linuxManagerKind' DESC
'Linux Manager: ca, router, user or external, the kind of a certificate'
EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256}
SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.8 NAME 'linuxManagerTemplate'
DESC 'Linux Manager: the template of a certificate' EQUALITY caseIgnoreMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.9 NAME
'linuxManagerSubjectAltName' DESC 'Linux Manager: a subject alternative name
of a certificate' EQUALITY caseIgnoreMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{256} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.10 NAME 'linuxManagerNotAfter'
DESC 'Linux Manager: when a certificate expires' EQUALITY
generalizedTimeMatch ORDERING generalizedTimeOrderingMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.11 NAME 'linuxManagerRevoked'
DESC 'Linux Manager: when a certificate was revoked' EQUALITY
generalizedTimeMatch ORDERING generalizedTimeOrderingMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.12 NAME
'linuxManagerRevocationReason' DESC 'Linux Manager: why a certificate was
revoked' EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256}
SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.24 NAME 'linuxManagerToken'
DESC 'Linux Manager: the Simple CA token that signs the issuing CAs'
EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 SINGLE-VALUE
)
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.25 NAME
'linuxManagerUpstreamName' DESC 'Linux Manager: the Simple CA issuing CA of
the token' EQUALITY caseIgnoreMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{256} SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.26 NAME
'linuxManagerCertificateChain' DESC 'Linux Manager: a certificate and its
chain, PEM' EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40
SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.27 NAME
'linuxManagerRequestKey' DESC 'Linux Manager: the private key of a CSR, PEM'
EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 SINGLE-VALUE
)
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.28 NAME
'linuxManagerCertificateName' DESC 'Linux Manager: the name a certificate is
filed under by the application that keeps it' EQUALITY caseExactMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{256} SINGLE-VALUE )
olcObjectClasses: ( 1.3.6.1.4.1.67380.10.1.2.2.2 NAME 'linuxManagerAuthority'
DESC 'Linux Manager: a CA of the PKI' SUP top STRUCTURAL MUST cn MAY (
cACertificate $ certificateRevocationList $ linuxManagerPrivateKey $
linuxManagerCertificateRequest $ linuxManagerCRLNumber $
linuxManagerCRLSource $ linuxManagerRetired $ linuxManagerToken $
linuxManagerUpstreamName ) )
olcObjectClasses: ( 1.3.6.1.4.1.67380.10.1.2.2.3 NAME
'linuxManagerCertificate' DESC 'Linux Manager: a certificate a CA of the PKI
issued' SUP top STRUCTURAL MUST serialNumber MAY ( cn $ userCertificate $
linuxManagerPrivateKey $ linuxManagerKind $ linuxManagerTemplate $
linuxManagerSubjectAltName $ linuxManagerNotAfter $ linuxManagerRevoked $
linuxManagerRevocationReason $ linuxManagerCertificateName ) )
olcObjectClasses: ( 1.3.6.1.4.1.67380.10.1.2.2.5 NAME
'linuxManagerHostCertificate' DESC 'Linux Manager: a certificate of the
server kept with its key' SUP top STRUCTURAL MUST cn MAY (
linuxManagerCertificateChain $ linuxManagerPrivateKey $
linuxManagerCertificateRequest $ linuxManagerRequestKey $ linuxManagerKind )
)
@@ -0,0 +1,67 @@
# Linux Manager's schema of its accounts, of the clients and resources of its OpenID Provider, and
# of the roles of those resources; the PKI is in linux-manager-pki.ldif.
#
# OIDs: the LDAP arc 1.3.6.1.4.1.67380.10.1.2 of OID-REGISTRY.txt, attribute types under .1 and
# object classes under .2.
dn: cn=linux-manager,cn=schema,cn=config
objectClass: olcSchemaConfig
cn: linux-manager
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.1 NAME 'linuxManagerScope'
DESC 'Linux Manager: an authorization scope of the account' EQUALITY
caseIgnoreMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{256} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.13 NAME
'linuxManagerConsoleLogin' DESC 'Linux Manager: whether the user may use a
console' EQUALITY booleanMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.7
SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.14 NAME
'linuxManagerConsoleAccount' DESC 'Linux Manager: the local account the
console of the user runs as' EQUALITY caseIgnoreMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{256} SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.15 NAME
'linuxManagerWireGuardPeer' DESC 'Linux Manager: a WireGuard peer of the
user, its public key and IPs' EQUALITY caseExactMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{1024} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.16 NAME 'linuxManagerPasskey'
DESC 'Linux Manager: a passkey of the user, its credential as JSON' EQUALITY
caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{4096} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.17 NAME
'linuxManagerRedirectUri' DESC 'Linux Manager: a redirect URI of an OpenID
Connect client' EQUALITY caseExactMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{1024} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.18 NAME
'linuxManagerPostLogoutRedirectUri' DESC 'Linux Manager: a post-logout
redirect URI of an OpenID Connect client' EQUALITY caseExactMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{1024} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.19 NAME
'linuxManagerAllowedGroup' DESC 'Linux Manager: a group whose members may
sign in to an OpenID Connect client' EQUALITY distinguishedNameMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.12 )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.20 NAME
'linuxManagerGrantType' DESC 'Linux Manager: a grant an OpenID Connect
client may use besides the authorization code' EQUALITY caseExactMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{64} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.21 NAME
'linuxManagerPublicClient' DESC 'Linux Manager: whether an OpenID Connect
client has no secret' EQUALITY booleanMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.7 SINGLE-VALUE )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.22 NAME
'linuxManagerClientScope' DESC 'Linux Manager: a scope of a resource an
OpenID Connect client may ask for' EQUALITY caseExactMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{128} )
olcAttributeTypes: ( 1.3.6.1.4.1.67380.10.1.2.1.23 NAME
'linuxManagerResourceScope' DESC 'Linux Manager: a scope of a resource of
the OpenID Provider' EQUALITY caseExactMatch SYNTAX
1.3.6.1.4.1.1466.115.121.1.15{64} )
olcObjectClasses: ( 1.3.6.1.4.1.67380.10.1.2.2.1 NAME 'linuxManagerAccount'
DESC 'Linux Manager: properties of a user or a Manager-only account' SUP top
AUXILIARY MAY ( mail $ linuxManagerScope $ displayName $ description $
linuxManagerConsoleLogin $ linuxManagerConsoleAccount $
linuxManagerWireGuardPeer $ linuxManagerPasskey $ linuxManagerRedirectUri $
linuxManagerPostLogoutRedirectUri $ linuxManagerAllowedGroup $
linuxManagerGrantType $ linuxManagerPublicClient $ linuxManagerClientScope $
linuxManagerResourceScope ) )
olcObjectClasses: ( 1.3.6.1.4.1.67380.10.1.2.2.4 NAME 'linuxManagerRole' DESC
'Linux Manager: a role of a resource of the OpenID Provider' SUP top
STRUCTURAL MUST cn MAY ( description $ member ) )
Executable
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Run the manager and the Vite development server on this workstation: dev.py CONFIG [CONNECTION].
CONFIG is the config.json of a platform. The server's address comes from the outputs of the
platform's root module, module_root of CONFIG, relative to its directory, read with its iac_tool
(terraform by default, or tofu). The sessions are kept in the database of the PostgreSQL connection
string CONNECTION, or without one in PGDATABASE (else the login name), with libpq's PG* variables
for the rest. The manager reads the generated dev.json, whose bind is 127.0.0.1, and listens on
127.0.0.1:7080; its Python packages are installed in .venv. The application is served at
http://localhost:5180 and passes /api to the manager. A wrong argument is a message on standard
error and the exit status 2.
"""
import getpass
import json
import os
import pathlib
import subprocess
import sys
ROOT = pathlib.Path(__file__).resolve().parent
SETTINGS = ROOT / 'dev.json'
VENV = ROOT / '.venv'
WEB = ROOT / 'web'
MANAGER = ROOT / 'debian-package' / 'src' / 'usr' / 'lib' / 'linux-manager' / 'manager'
def main():
if not 2 <= len(sys.argv) <= 3:
print(f'usage: {sys.argv[0]} <platform config.json> [PostgreSQL connection string]', file=sys.stderr)
return 2
config = pathlib.Path(sys.argv[1]).resolve()
if not config.is_file():
print(f'dev.py: {sys.argv[1]} does not exist', file=sys.stderr)
return 2
database = sys.argv[2] if len(sys.argv) == 3 else f'dbname={os.environ.get("PGDATABASE") or getpass.getuser()}'
platform = json.loads(config.read_text(encoding='utf-8'))
root = platform.get('module_root')
if not isinstance(root, str) or not root.strip() or os.path.isabs(root):
print(f'dev.py: module_root in {config} must be a directory relative to {config.parent}', file=sys.stderr)
return 2
module_root = pathlib.Path(os.path.normpath(config.parent / root))
if not module_root.is_dir():
print(f'dev.py: module_root {module_root} is not a directory', file=sys.stderr)
return 2
SETTINGS.write_text(json.dumps({'terraform_dir': str(module_root), 'database': database,
'iac_tool': platform.get('iac_tool') or 'terraform', 'bind': '127.0.0.1'}) + '\n',
encoding='utf-8')
# The manager's packages in .venv, and the application's in node_modules, installed when missing or older.
python = VENV / 'bin' / 'python'
if not os.access(python, os.X_OK):
subprocess.run([sys.executable, '-m', 'venv', str(VENV)], check=True)
if subprocess.run([str(python), '-c', 'import psycopg, requests'], stderr=subprocess.DEVNULL).returncode != 0:
subprocess.run([str(VENV / 'bin' / 'pip'), 'install', '--quiet', 'psycopg[binary]', 'requests'], check=True)
modules, lock = WEB / 'node_modules', WEB / 'package-lock.json'
if not modules.is_dir() or lock.stat().st_mtime > modules.stat().st_mtime:
subprocess.run(['npm', 'install'], cwd=WEB, check=True)
manager = subprocess.Popen([str(python), str(MANAGER), '--config', str(SETTINGS)])
try:
print(f'Platform module: {module_root}', flush=True)
return subprocess.run(['npm', 'run', 'dev'], cwd=WEB,
env={**os.environ, 'VITE_MANAGER': 'http://127.0.0.1:7080'}).returncode
except KeyboardInterrupt:
return 130
finally:
manager.terminate()
manager.wait()
if __name__ == '__main__':
sys.exit(main())
-65
View File
@@ -1,65 +0,0 @@
#!/bin/sh
# Run the manager and the Vite development server on this workstation.
# Usage: ./dev.sh <platform config.json> [PostgreSQL connection string]
# The server's address comes from the outputs of the platform's root module, module_root of that
# config.json, relative to its directory, read with its iac_tool; the sessions are kept in the database of the connection
# string, or without one in PGDATABASE (else the login name) with libpq's PG* variables for the
# rest. The manager reads the generated dev.json, whose bind is 127.0.0.1, and listens on 127.0.0.1:7080; its Python packages
# are installed in .venv. The application is served at http://localhost:5180 and passes /api to the
# manager.
set -e
if [ $# -lt 1 ] || [ $# -gt 2 ]; then
printf 'Usage: %s <platform config.json> [PostgreSQL connection string]\n' "$0" >&2
exit 2
fi
DATABASE="${2:-dbname=${PGDATABASE:-$(id -un)}}"
if [ ! -f "$1" ]; then
printf 'ERROR: %s does not exist.\n' "$1" >&2
exit 2
fi
ROOT="$(cd "$(dirname "$0")" && pwd)"
SETTINGS="$ROOT/dev.json"
PLATFORM_CONFIG="$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"
MODULE_ROOT="$(python3 - "$PLATFORM_CONFIG" <<'EOF'
import json, os, sys
path = sys.argv[1]
root = json.load(open(path, encoding='utf-8')).get('module_root')
if not isinstance(root, str) or not root.strip() or os.path.isabs(root):
sys.exit(f'module_root in {path} must be a directory relative to {os.path.dirname(path)}')
print(os.path.normpath(os.path.join(os.path.dirname(path), root)))
EOF
)"
# The tool that reads the outputs is the platform's, iac_tool of its config.json: tofu or terraform.
IAC_TOOL="$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1], encoding="utf-8")).get("iac_tool") or "terraform")' "$PLATFORM_CONFIG")"
if [ ! -d "$MODULE_ROOT" ]; then
printf 'ERROR: module_root %s is not a directory.\n' "$MODULE_ROOT" >&2
exit 2
fi
python3 - "$SETTINGS" "$MODULE_ROOT" "$DATABASE" "$IAC_TOOL" <<'EOF'
import json, sys
with open(sys.argv[1], 'w', encoding='utf-8') as handle:
json.dump({'terraform_dir': sys.argv[2], 'database': sys.argv[3], 'iac_tool': sys.argv[4], 'bind': '127.0.0.1'}, handle)
handle.write('\n')
EOF
if [ ! -x "$ROOT/.venv/bin/python" ]; then
python3 -m venv "$ROOT/.venv"
fi
if ! "$ROOT/.venv/bin/python" -c 'import psycopg, requests' 2>/dev/null; then
"$ROOT/.venv/bin/pip" install --quiet 'psycopg[binary]' requests
fi
cd "$ROOT/web"
if [ ! -d node_modules ] || [ package-lock.json -nt node_modules ]; then
npm install
fi
"$ROOT/.venv/bin/python" "$ROOT/debian-package/src/usr/lib/linux-manager/manager" --config "$SETTINGS" &
MANAGER=$!
trap 'kill $MANAGER 2>/dev/null' EXIT INT TERM
echo "Platform module: $MODULE_ROOT"
VITE_MANAGER=http://127.0.0.1:7080 npm run dev
+3 -3
View File
@@ -11,11 +11,11 @@ for what the package itself does.
up).
- An SSH key pair for `admin_ssh_public_key`.
- A build of the `linux-manager` package published to the repository at `repo_url` (default: the
project's Gitea Debian registry). See [../../debian-package](../../debian-package) for
`build.sh`/`publish.sh`.
project's Gitea Debian registry). See [Building](../../README.md#building) for
`build.py`/`publish.py`.
- That repository must allow anonymous reads, since the server pulls the package with no
credentials configured. On Gitea this means the `debian` package registry under the
`slawek` account is set to public/anonymous-read; `publish.sh` still authenticates to
`slawek` account is set to public/anonymous-read; `publish.py` still authenticates to
upload, only reads are anonymous. This is a one-time change made on the Gitea side, outside
this repository.
+2 -2
View File
@@ -12,8 +12,8 @@ repository's top-level [README](../../README.md) for what the package itself doe
or a service account).
- An SSH key pair for `admin_ssh_public_key`.
- A build of the `linux-manager` package published to the repository at `repo_url` (default: the
project's Gitea Debian registry). See [../../debian-package](../../debian-package) for
`build.sh`/`publish.sh`. That repository must allow anonymous reads, since the server pulls
project's Gitea Debian registry). See [Building](../../README.md#building) for
`build.py`/`publish.py`. That repository must allow anonymous reads, since the server pulls
the package with no credentials configured.
## Usage
Executable
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Upload the package built for the newest CHANGELOG.md entry to the Gitea Debian repository: publish.py.
The package is out/PACKAGE_VERSION_all.deb, its name the Source of debian/control and its version
the Debian version of the newest entry of CHANGELOG.md (bin/changelog.py), which build.py builds.
It is uploaded to the component main of each distribution of DISTRIBUTIONS (resolute by default,
separated by spaces) of the owner OWNER (koszewscy by default) at SERVER_URL
(https://gitea.koszewscy.waw.pl by default), signed in as OWNER with the token PACKAGES_TOKEN, else
the content of ~/.gitea-packages-token. A distribution that has the version already (Gitea's 409)
is skipped. A failure is a message on standard error and the exit status 1.
"""
import base64
import os
import pathlib
import sys
import urllib.error
import urllib.request
ROOT = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT / 'bin'))
import changelog # noqa: E402
CHANGELOG = ROOT / 'CHANGELOG.md'
CONTROL = ROOT / 'debian-package' / 'debian' / 'control'
TOKEN_FILE = pathlib.Path.home() / '.gitea-packages-token'
def main():
owner = os.environ.get('OWNER') or 'koszewscy'
server = (os.environ.get('SERVER_URL') or 'https://gitea.koszewscy.waw.pl').rstrip('/')
distributions = (os.environ.get('DISTRIBUTIONS') or 'resolute').split()
try:
found = changelog.entries(CHANGELOG.read_text(encoding='utf-8'))
package = changelog.control_field(CONTROL.read_text(encoding='utf-8'), 'Source')
if not found:
raise ValueError('no entry')
token = os.environ.get('PACKAGES_TOKEN') or TOKEN_FILE.read_text(encoding='utf-8').strip()
except (OSError, ValueError) as error:
sys.exit(f'publish.py: {error}')
version = changelog.debian_version(found[0]['version'])
deb = ROOT / 'out' / f'{package}_{version}_all.deb'
if not deb.is_file():
sys.exit(f'publish.py: {deb.relative_to(ROOT)} does not exist; run ./build.py first')
content = deb.read_bytes()
credentials = base64.b64encode(f'{owner}:{token}'.encode()).decode()
for distribution in distributions:
request = urllib.request.Request(f'{server}/api/packages/{owner}/debian/pool/{distribution}/main/upload',
data=content, method='PUT',
headers={'Authorization': f'Basic {credentials}',
'Content-Type': 'application/octet-stream'})
try:
with urllib.request.urlopen(request, timeout=300):
print(f'{package} {version} is published in {distribution}/main.')
except urllib.error.HTTPError as error:
if error.code != 409:
sys.exit(f'publish.py: the upload to {distribution}/main returned HTTP {error.code}: '
f'{error.read().decode(errors="replace").strip()}')
print(f'{package} {version} is already in {distribution}/main, skipping.')
except urllib.error.URLError as error:
sys.exit(f'publish.py: {server} cannot be reached: {error.reason}')
return 0
if __name__ == '__main__':
sys.exit(main())
-48
View File
@@ -1,48 +0,0 @@
#!/bin/sh
set -e
# CONTAINER_RUNTIME from the environment, for example docker with DOCKER_CONTEXT naming a remote engine;
# otherwise Apple container CLI on macOS and Docker CE on Linux.
if [ -z "${CONTAINER_RUNTIME:-}" ]; then
case "$(uname -s)" in
Darwin) CONTAINER_RUNTIME=container ;;
Linux) CONTAINER_RUNTIME=docker ;;
*) printf 'ERROR: unsupported platform %s\n' "$(uname -s)" >&2; exit 1 ;;
esac
fi
OWNER="${OWNER:-koszewscy}"
SERVER_URL="${SERVER_URL:-https://gitea.koszewscy.waw.pl}"
PACKAGES_TOKEN="${PACKAGES_TOKEN:-$(cat ~/.gitea-packages-token)}"
# The Ubuntu releases whose distribution of the repository gets the package, in its component main.
DISTRIBUTIONS="${DISTRIBUTIONS:-resolute}"
# Reads the changelog copied into the builder image, so no bind mount is needed.
changelog_field() {
$CONTAINER_RUNTIME run --rm linux-manager-builder \
dpkg-parsechangelog --show-field "$1" -l /build/src/debian/changelog
}
VERSION="$(changelog_field Version)"
PACKAGE="$(changelog_field Source)"
DEB="out/${PACKAGE}_${VERSION}_all.deb"
if [ ! -f "$DEB" ]; then
printf 'ERROR: %s does not exist. Run ./build.sh first.\n' "$DEB" >&2
exit 1
fi
BODY="$(mktemp)"
trap 'rm -f "$BODY"' EXIT
# Gitea answers 409 for a version that is in the distribution already.
for DISTRIBUTION in $DISTRIBUTIONS; do
STATUS="$(curl -s -o "$BODY" -w '%{http_code}' --user "$OWNER:$PACKAGES_TOKEN" \
--upload-file "$DEB" \
"$SERVER_URL/api/packages/$OWNER/debian/pool/$DISTRIBUTION/main/upload")"
case "$STATUS" in
2??) printf '%s %s is published in %s/main.\n' "$PACKAGE" "$VERSION" "$DISTRIBUTION" ;;
409) printf '%s %s is already in %s/main, skipping.\n' "$PACKAGE" "$VERSION" "$DISTRIBUTION" ;;
*) printf 'ERROR: the upload to %s/main returned HTTP %s: %s\n' "$DISTRIBUTION" "$STATUS" "$(cat "$BODY")" >&2; exit 1 ;;
esac
done
+70 -60
View File
@@ -1,25 +1,39 @@
#!/usr/bin/env python3
"""Commit everything, tag the version of the newest changelog entry and push main with the tags.
"""Commit everything with the summary of the newest CHANGELOG.md entry; with --push, tag its version and push main and the tag.
The tag is the version of the first entry of debian-package/debian/changelog, without the
Debian revision 1: linux-manager (0.5.1-1) is tagged 0.5.1 and (0.5.1-2) 0.5.1-2. The tag
starts the release workflow. Once the release succeeds, .dev-build.serial, the serial of the last
dev build (bin/lm-dev-build.py), is written as 0, so the dev builds of the next entry start at
~dev1.
The newest entry of CHANGELOG.md (bin/changelog.py reads it) is released: its heading gets the
current time, "## 0.5.1 - 2026-11-24 10:00:00 +0100", and everything is committed with its summary
paragraph, its lines joined, as the message. The commit marks the entry as released: a second run
for the same entry is refused, and the next change needs a new entry. With --push, the version of
the heading is tagged, 0.5.1 or 0.5.1-2, and main and the tag are pushed in one atomic push; the tag
starts the release workflow. With --no-tag, the entry is an internal release: it is committed as
without --push, and --push pushes main without a tag. debian/changelog is not kept in the
repository; the build writes it from CHANGELOG.md.
Once a release is committed, LXD_DEV_BUILD_SERIAL of .lm-dev-config/settings.json, the serial of
the last dev build (bin/lm-dev-build.py), is written as 0 when the file exists, so the dev builds
of the next entry start at ~dev1. -n prints what would change and the git commands instead.
"""
import argparse
import datetime
import json
import pathlib
import shlex
import subprocess
import sys
ROOT = pathlib.Path(__file__).resolve().parent
CHANGELOG = ROOT / 'debian-package' / 'debian' / 'changelog'
DEV_SERIAL = ROOT / '.dev-build.serial'
sys.path.insert(0, str(ROOT / 'bin'))
import changelog # noqa: E402
CHANGELOG = ROOT / 'CHANGELOG.md'
#: The settings of the lm-dev scripts, which hold LXD_DEV_BUILD_SERIAL.
DEV_SETTINGS = ROOT / '.lm-dev-config' / 'settings.json'
#: Print the git commands instead of running them; set by -n/--dry-run.
#: Print the changes and the git commands instead of making them; set by -n/--dry-run.
DRY_RUN = False
@@ -34,67 +48,63 @@ def git(*args):
sys.exit(result.returncode)
def summary():
"""The summary of the first changelog entry joined into one line, or None when it has none.
The summary is the entry's first paragraph: lines indented by exactly two spaces, the
first not a "*" item, with a blank line between it and the header and a blank line after it.
"""
lines = CHANGELOG.read_text(encoding='utf-8').splitlines()
if len(lines) < 4 or lines[1].strip():
return None
paragraph = []
for line in lines[2:]:
if not line.strip():
break
if not line.startswith(' ') or line.startswith(' ') or line.startswith(' -- '):
return None
paragraph.append(line.strip())
else:
return None
if not paragraph or paragraph[0].startswith('*'):
return None
return ' '.join(paragraph)
def version():
"""The tag of the first changelog entry: its version, without the Debian revision when that is 1."""
first = CHANGELOG.read_text(encoding='utf-8').splitlines()[0]
start, end = first.find('('), first.find(')')
if start == -1 or end < start:
sys.exit(f'{CHANGELOG}: the first line has no version: {first}')
full = first[start + 1:end]
upstream, _, revision = full.rpartition('-')
return upstream if upstream and revision == '1' else full
def main():
global DRY_RUN
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('-m', '--message', help='commit message; default: the summary of the newest changelog entry, a paragraph not starting with "*" between blank lines right after its header')
parser.add_argument('-n', '--dry-run', action='store_true', help='print the git commands instead of running them')
parser.add_argument('--no-push', action='store_true', help='commit and tag, but do not push')
parser.add_argument('-n', '--dry-run', action='store_true',
help='print the changes and the git commands instead of making them')
parser.add_argument('--push', action='store_true', help='also tag the release and push main and the tag')
parser.add_argument('--no-tag', action='store_true',
help='make an internal release: with --push, push main alone, without a tag')
args = parser.parse_args()
DRY_RUN = args.dry_run
message = args.message or summary()
if not message:
sys.exit(f'no commit message: pass -m, or start the newest entry of {CHANGELOG} with a summary paragraph '
'not starting with "*", indented by two spaces, with a blank line above and below it')
tag = version()
text = CHANGELOG.read_text(encoding='utf-8')
try:
found = changelog.entries(text)
except ValueError as error:
sys.exit(f'{CHANGELOG}: {error}')
if not found or not found[0]['summary']:
sys.exit(f'start the newest entry of {CHANGELOG} with a summary paragraph between blank lines right after '
'its heading')
newest = found[0]
message, tag = newest['summary'], newest['version']
if subprocess.run(['git', 'rev-parse', '-q', '--verify', f'refs/tags/{tag}'], cwd=ROOT,
capture_output=True).returncode == 0:
sys.exit(f'tag {tag} exists; add a new changelog entry first')
git('add', '-A')
git('commit', '-m', message)
git('tag', tag)
if not args.no_push:
git('push', 'origin', 'main', '--tags')
if DRY_RUN:
print(f'echo 0 > {shlex.quote(str(DEV_SERIAL))}')
else:
DEV_SERIAL.write_text('0\n', encoding='utf-8')
log = subprocess.run(['git', 'log', '--format=%s'], cwd=ROOT, capture_output=True, text=True)
committed = log.returncode == 0 and message in log.stdout.splitlines()
dirty = subprocess.run(['git', 'status', '--porcelain'], cwd=ROOT, capture_output=True,
text=True).stdout.strip() != ''
if committed and dirty:
sys.exit(f'{tag} is released; add a new changelog entry for the changes')
if committed and not args.push:
sys.exit(f'{tag} is released; add a new changelog entry, or publish it with --push')
if not committed and not dirty:
sys.exit(f'nothing to commit for {tag}')
if not committed:
if newest['date'] is None:
heading = f'## {tag} - {datetime.datetime.now().astimezone().strftime(changelog.DATE_FORMAT)}'
if DRY_RUN:
print(f'# {CHANGELOG.name}: {heading}')
else:
lines = text.splitlines(keepends=True)
lines[newest['line']] = heading + '\n'
CHANGELOG.write_text(''.join(lines), encoding='utf-8')
git('add', '-A')
git('commit', '-m', message)
if DRY_RUN:
print(f'# LXD_DEV_BUILD_SERIAL of {DEV_SETTINGS} set to 0')
elif DEV_SETTINGS.is_file():
settings = json.loads(DEV_SETTINGS.read_text(encoding='utf-8'))
settings['LXD_DEV_BUILD_SERIAL'] = 0
DEV_SETTINGS.write_text(json.dumps(settings, indent=2) + '\n', encoding='utf-8')
if args.push and args.no_tag:
git('push', 'origin', 'main')
elif args.push:
git('tag', tag)
git('push', '--atomic', 'origin', 'main', tag)
return 0
+44 -24
View File
@@ -30,7 +30,7 @@ export LXD_POOL=...
```
```sh
./build.sh
./build.py
bin/lm-dev-run.py core nat s2s
```
@@ -54,7 +54,7 @@ its end. Its first instance is its Vault, `lm-vault` on the bridge `lmt-vault` (
reached by the Mac and the instances on the LXD host's address, port 8200, through a proxy
device; every secret reaches an instance through it (see Secrets). The administrator password and
the pre-shared key are generated per run and kept in the scenario's Vault, as `<server>/admin` and
`<server>/config`; with `--keep` they stay there. The run leaves `.env` as it is.
`<server>/config`; with `--keep` they stay there.
The run prints PASS, FAIL or SKIP per check and exits non-zero on a failure; WireGuard is skipped
when the host kernel has no WireGuard module.
@@ -91,27 +91,44 @@ and alice's password and OpenVPN profile take this way; the admin password is al
`<name>/admin`. A WireGuard client's private key is made in the client and never leaves it.
A user's TOTP token is the key `<vm>-<user>` of the TOTP engine. The VM has the Vault generate it
with `lm-dev-vault totp` and enrols its secret with its current code; the secret is never on the
Mac and cannot be read back from the Vault, which gives the codes (`totp/code/<vm>-<user>`).
with `lm-dev-vault totp` and enrols its secret with its current code; the secret cannot be read
back from the Vault, which gives the codes (`totp/code/<vm>-<user>`). For the administrator of a VM
made by `lm-dev-vm.py`, the Mac also reads the key's otpauth URL from the VM before the VM removes
its copy, and keeps it as `otp_url` with the password, to add the token to an authenticator app.
`lm-dev-vm.py remove` deletes the VM's role, policy, secrets and TOTP keys.
The Vault's web UI is at `/ui` of its address, `http://<vault-address>:8200/ui`; it signs in with
the root token of `vault-<project>.json`.
The state the scripts keep across clean-ups of `tmp/` is in `.lm-dev-config/` at the repository's
root, mode 0700, its files 0600, ignored by git: the project's state and repository key, the
Vault's address, unseal key and root token (`vault-<project>.json`). `tmp/` holds
only what can go: logs and files removed right after use.
root, mode 0700, its files 0600, ignored by git: the scripts' settings (`settings.json`), the
project's state and repository key, the Vault's address, unseal key and root token
(`vault-<project>.json`) and the administrator of each VM `lm-dev-vm.py` made, its `username`,
`password` and the otpauth URL of its TOTP token, `otp_url` (`vm-<project>-<vm>.json`). `tmp/` holds only what can go: logs and files removed right after use.
Each variable of the option tables below, and `LXD_DEV_BUILD_SERIAL`, the serial of the last dev
build (see `lm-dev-build.py` below), is read from the environment, else from `settings.json`, a
JSON object of the variables and their values, else it takes its default. A variable without a
default, such as `LXD_REMOTE`, is required: without its option, the script stops and names it.
```json
{
"LXD_REMOTE": "my-remote",
"LXD_POOL": "default",
"LXD_FORWARD_ADDRESS": "192.0.2.10"
}
```
## A VM to work with
`lm-dev-vm.py create` launches one server VM, `lm-dev` by default, on the LXD remote and leaves
`lm-dev-vm.py create` launches one server VM, `router` by default, on the LXD remote and leaves
it running. The VM is created in a project, the test project `lm-dev` by default, with that
project's default profile, and takes its address from DHCP. It gets the package with the
administrator `admin` and a generated password, set as `ADMIN_USERNAME` and `ADMIN_PASSWORD` in the
repository's `.env`, a TOTP token for `admin` in the project's Vault unless `--no-otp` is given,
and a configuration from `configs/`, `core.json` by default; `@ETH0@` is the interface of the VM's
default route.
administrator `admin`, whose password and TOTP token, unless `--no-otp` is given, are `password` and
`otp_url` of `.lm-dev-config/vm-<project>-<vm>.json`, and a configuration from `configs/`,
`core.json` by default; `@ETH0@` is the interface of the VM's default route. A password or
`otp_url` the file lacks, or both when there is no file, is generated and kept in the file, so a VM
made again has the same password and token; delete one from the file to have a new one made.
In a test project made by `lm-dev-lxd-project.py`, the VM installs the package from the project's
repository, so later dev builds reach it as updates; in another project it installs `--deb`, or
@@ -141,14 +158,15 @@ bin/lm-dev-vm.py remove
`create` needs the project's Vault (`lm-dev-lxd-project.py vault create`): the VM gets its
AppRole there, and reads the preseed and the configuration, kept as `<vm>/preseed` and
`<vm>/config`, and creates the TOTP key `<vm>-admin` with it. `remove` deletes the VM, its forward
and what the Vault keeps for it; `.env` is left as it is. Options:
`<vm>/config`; the TOTP key `<vm>-admin` is made from `otp_url`, or else the VM has the Vault
generate it. `remove` deletes the VM, its forward and what the Vault keeps for it, and keeps
`vm-<project>-<vm>.json`. Options:
| Option | Variable | Default | Meaning |
|---|---|---|---|
| `--remote` | `LXD_REMOTE` | required | The `lxc` remote |
| `--project` | `LXD_PROJECT` | `lm-dev` | The project of the VM |
| `--vm` | | `lm-dev` | The name of the VM; it must not exist for `create` |
| `--vm` | | `router` | The name of the VM; it must not exist for `create` |
| `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of the VM |
| `--config` | | `core.json` | The configuration from `configs/` |
| `--listen` | `LXD_LISTEN` | the remote URL's host | Outside a test project, the address the proxies listen on |
@@ -228,12 +246,12 @@ bin/lm-dev-lxd-project.py remove
| `--ovn-ranges` | `LXD_UPLINK_OVN_RANGES` | required by `uplink setup` | LAN addresses for OVN routers |
| `--routes` | `LXD_UPLINK_ROUTES` | required by `uplink setup` | A LAN subnet for network forwards |
`lm-dev-build.py` builds and publishes the next dev build. Its version is the newest changelog
entry's with `~dev<N>` before the Debian revision, `0.41.0~dev7-1` for `0.41.0-1`, so the release
of that entry is newer than its dev builds. `N` is that of the last dev build, kept in
`.dev-build.serial` of the repository; each build that succeeds writes its own, one higher, and
`release.py` writes 0 when it releases, so the next entry's builds start at `~dev1`. `./build.sh`
builds it, with `CONTAINER_RUNTIME` and `DOCKER_CONTEXT` from the environment; the build is moved to `out/dev/`, copied into the repository and published there. A
`lm-dev-build.py` builds and publishes the next dev build. Its version is the Debian version of
the newest entry of `CHANGELOG.md` with `~dev<N>` before the Debian revision, `0.41.0~dev7-1` for
`0.41.0`, so the release of that entry is newer than its dev builds. `N` is that of the last dev build,
`LXD_DEV_BUILD_SERIAL`, 0 by default; each build that succeeds writes its own, one higher, into
`.lm-dev-config/settings.json`, and `release.py` writes 0 there when it releases, so the next
entry's builds start at `~dev1`. `./build.py` builds it, with `CONTAINER_RUNTIME` and `DOCKER_CONTEXT` from the environment; the build is moved to `out/dev/`, copied into the repository and published there. A
VM of the project then gets it with Check update and Upgrade in the Manager, or `apt-get update`
and `apt-get upgrade`.
@@ -246,10 +264,12 @@ read from its state file, so the script takes no `--remote`.
## A TOTP token for a user of a test VM
`bin/lm-dev-otp-register.py` enrols a new TOTP token for a user of a VM, `admin` of `lm-dev` by
`bin/lm-dev-otp-register.py` enrols a TOTP token for a user of a VM, `admin` of `router` by
default, replacing a token the user had. The project's Vault generates the key `<vm>-<user>` in its
TOTP engine and hands it to the VM (see Secrets), where the package's `linuxmanager_users` stores
it. `bin/lm-dev-otp-code.py` prints the user's current code, read from the Vault, for the Manager's
it. For the VM's administrator, the key is made from `otp_url` in `vm-<project>-<vm>.json` when the
file has it, and a generated key's URL is kept there as `otp_url`.
`bin/lm-dev-otp-code.py` prints the user's current code, read from the Vault, for the Manager's
sign-in, SSH or `sudo`.
```sh
@@ -264,7 +284,7 @@ bin/lm-dev-otp-code.py
|---|---|---|---|
| `--remote` | `LXD_REMOTE` | required by `lm-dev-otp-register.py` | The `lxc` remote |
| `--project` | `LXD_PROJECT` | `lm-dev` | The project of the VM |
| `--vm` | | `lm-dev` | The name of the VM |
| `--vm` | | `router` | The name of the VM |
| `--user` | | `admin` | The user |
## A command-line authenticator app