Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
240255b2ff | ||
|
|
5c6fd90f37 | ||
|
|
64c3ae4c36 | ||
|
|
7efacfa3bb | ||
|
|
0cec95c19b | ||
|
|
4b5318c676 | ||
|
|
b61d1593b7 | ||
|
|
6911d16fa3 |
No files matched your search
@@ -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
-2
@@ -15,7 +15,6 @@ tmp
|
||||
node_modules
|
||||
web/dist
|
||||
.venv
|
||||
dev.json
|
||||
/.dev-build.serial
|
||||
**/.env
|
||||
/.lm-dev-config/
|
||||
/debian-package/debian/changelog
|
||||
@@ -538,12 +538,13 @@ Decision: Caddy, the `caddy` package of the Ubuntu archive and a dependency of t
|
||||
`127.0.0.1:9474` and rclone's WebDAV on `127.0.0.1:7446`, and Caddy calls them there. Once the
|
||||
server is configured, `linux-manager-setup` writes `/etc/caddy/linux-manager.Caddyfile`: plain
|
||||
HTTP sites on `web.port` (7081), the Manager's `port` (7080) and, while metrics are on,
|
||||
`metrics.port` (9464), on every address; while `https.enabled` is `true` and `wan.local_fqdn` is
|
||||
set, sites for `wan.local_fqdn` on `https.web_port` (7444), `https.manager_port` (7443),
|
||||
`metrics.https_port` (9465) and `sites.webdav_port` (7445). While HTTPS is on, the Manager's plain
|
||||
HTTP site redirects (308) to its HTTPS address unless `https.disable_auto_redirect` is set; the
|
||||
status page's never does, so monitors and clients that do not trust the server's certificate
|
||||
keep reaching it. The `listen` settings choose the interfaces the firewall opens each plain HTTP
|
||||
`metrics.port` (9464), on every address; and always sites for the HTTPS names (ADR-65) on
|
||||
`https.web_port` (7444), `https.manager_port` (7443), `metrics.https_port` (9465) and
|
||||
`sites.webdav_port` (7445). Unless `https.disable_auto_redirect` is set, both plain HTTP sites
|
||||
redirect (308) a request for an HTTPS name to the same host on HTTPS, and the Manager's redirects
|
||||
every other request to the first HTTPS name; the status page stays on plain HTTP by address, so
|
||||
monitors and clients that do not trust the server's certificate keep reaching it, and `/pki/`
|
||||
stays on plain HTTP on both, where the certificates name it. The `listen` settings choose the interfaces the firewall opens each plain HTTP
|
||||
port on, as Caddy listens on every address. The certificate comes from `https.certificate`
|
||||
(ADR-60); with `acme`, Caddy obtains and renews it with the HTTP challenge on port 80, which the
|
||||
firewall opens on the external interface then; `auto_https disable_redirects` keeps port 80 to the
|
||||
@@ -812,30 +813,34 @@ P2S access. A server whose root should be elsewhere is set up with that source f
|
||||
the source of an existing root is not changed. The server
|
||||
keeps the users' keys, as the OpenVPN profile embeds them.
|
||||
|
||||
## ADR-28: CA certificates and CRLs are published at configurable endpoints, and CRLs are short-lived
|
||||
## ADR-28: CA certificates and CRLs are always published over plain HTTP, and CRLs are short-lived
|
||||
|
||||
Status: Accepted
|
||||
|
||||
Context: Clients outside the server, such as Windows and servers using the general-purpose CAs,
|
||||
find the issuer's certificate and the CRL through the AIA and CRL distribution point extensions,
|
||||
and cache a CRL until its next update. The server's CRLs were valid for ten years and published
|
||||
nowhere. Caddy serves files itself, and the web service already answers on the status port.
|
||||
nowhere. Caddy fronts every web port of the server: the status web service's and the Manager's, over
|
||||
plain HTTP and HTTPS. A client fetching an AIA certificate or a CRL may not follow a redirect, and
|
||||
checking the revocation of an HTTPS server's certificate over HTTPS depends on itself.
|
||||
|
||||
Decision: `pki.publish` lists the endpoints, in the order the URLs appear in the certificates:
|
||||
plain HTTP on the status port, served by the web service; plain HTTP on port 80, HTTPS on the
|
||||
status HTTPS port and HTTPS on port 443, served by Caddy's `file_server`. The files are DER, as
|
||||
RFC 5280 asks of these URLs, copied to `/var/lib/linux-manager/pki-publish`, outside the 0700 PKI
|
||||
directory, so that Caddy's user reads them. Ports 80 and 443 serve only the CA files and are opened
|
||||
on both interfaces when chosen. The CRLs of the issuing CAs are valid for `pki.crl_days`, a week
|
||||
by default, signed again at every revocation and by a daily timer once half their validity has
|
||||
passed; the root CRL has its own `pki.root_crl_days`, half a year by default, so an offline root
|
||||
needs its CRL signed twice a year, not weekly.
|
||||
Decision: the files are always published; there is no setting. Caddy's `file_server` serves them
|
||||
at `/pki/` on `web.port` and on the Manager's port, ahead of the Manager's redirect to HTTPS, and
|
||||
on `https.web_port` and `https.manager_port`, with the content types RFC 5280 gives. The
|
||||
certificates name only the plain HTTP URLs: the status port while the status web service is
|
||||
enabled, then the Manager's port, which always exists. The files are DER, copied to
|
||||
`/var/lib/linux-manager/pki-publish`, outside the 0700 PKI directory, so that Caddy's user reads
|
||||
them. The CRLs of the issuing CAs are valid for `pki.crl_days`, a week by default, signed again at
|
||||
every revocation and by a daily timer once half their validity has passed; the root CRL has its own
|
||||
`pki.root_crl_days`, half a year by default, so an offline root needs its CRL signed twice a year,
|
||||
not weekly.
|
||||
|
||||
Consequences: A client that caches a CRL sees a revocation within a week. The URLs are fixed in a
|
||||
certificate when it is signed, so a change of the endpoints or of `wan.local_fqdn` applies to
|
||||
certificates signed afterwards. HTTPS URLs are offered for clients that cannot use plain HTTP,
|
||||
although a client checking the revocation of the HTTPS server's own certificate cannot use them;
|
||||
Caddy's certificate is Let's Encrypt's, so the server's endpoints do not depend on themselves.
|
||||
Consequences: A client that caches a CRL sees a revocation within a week. A client tries the URLs
|
||||
in order, so one that cannot reach the status port falls back to the Manager's. The files are
|
||||
reachable where the firewall opens those ports: `web.listen` and the Manager's `listen` decide.
|
||||
The URLs are fixed in a certificate when it is signed, so a change of the ports or of
|
||||
`wan.local_fqdn` applies to certificates signed afterwards. A `pki.publish` of an earlier version
|
||||
is left out when the settings are read.
|
||||
|
||||
## ADR-29: Site-to-site connections authenticate with a pre-shared key or certificates
|
||||
|
||||
@@ -1408,19 +1413,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 +1489,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 +1575,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 +1637,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
|
||||
@@ -1689,11 +1705,12 @@ appliances, and ACME is used only when it is set to `acme`: a public name that r
|
||||
server and port 80 reachable from the internet are rarely ready when a server is installed. The
|
||||
file a new installation writes has it empty, and that installation's first setup chooses it and
|
||||
writes it into the file: `ca` when the Servers Issuing CA has its certificate after the PKI is
|
||||
provisioned, as with a root the server creates, else `self-signed`. An upgrade makes no choice: a
|
||||
configuration that names a source keeps it, and one that names none is self-signed. Whether
|
||||
HTTPS is on is an installer question and is always respected, and so is
|
||||
`https.disable_auto_redirect`, which keeps Caddy's plain HTTP site of the Manager from
|
||||
redirecting to HTTPS (ADR-21).
|
||||
provisioned, as with a root the server creates, else `self-signed`. Until a setup run has
|
||||
succeeded, a file that does not set it is taken as empty, so a configuration written by hand or by
|
||||
a tool in place of the installer's file gets the same choice. An upgrade makes no choice: a
|
||||
configuration that names a source keeps it, and once a run has succeeded, one that names none is
|
||||
self-signed. `https.disable_auto_redirect`, an installer question, is always respected; it keeps
|
||||
Caddy's plain HTTP sites from redirecting to HTTPS (ADR-21).
|
||||
|
||||
Consequences: A browser trusts a self-signed certificate, or one of the server's PKI, only once
|
||||
its user trusts it or the root. An imported certificate is not renewed by the server, which warns
|
||||
@@ -1785,3 +1802,55 @@ 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.
|
||||
|
||||
## ADR-65: HTTPS is always on, for wan.local_fqdn or the host name, with IP addresses on request
|
||||
|
||||
Status: Accepted
|
||||
|
||||
Context: The status page and the Manager carry passwords, so they are to be served over HTTPS on
|
||||
every server; only the redirect from plain HTTP is a choice, for labs and development, where the
|
||||
name of a server behind a forward is the only way to reach it. A server without `wan.local_fqdn`,
|
||||
such as the first device of a network without DNS, still needs a name for its certificate, and an
|
||||
appliance that is set up by address needs a certificate that names its address.
|
||||
|
||||
Decision: HTTPS has no switch: `https.enabled` and the installer's question are gone, and a file
|
||||
that still has the setting loads without it. The HTTPS names are `wan.local_fqdn` alone when it is
|
||||
set, else the host name and `<host name>.local`, which Avahi announces with mDNS on the internal
|
||||
side while there is no FQDN. `https.ip_sans`, off by default, adds the server's addresses to the
|
||||
self-signed certificate and the Servers Issuing CA's, and Caddy then serves HTTPS on them too; an
|
||||
ACME certificate names `wan.local_fqdn` only, which `acme` requires. Unless
|
||||
`https.disable_auto_redirect` is set, a plain HTTP request for an HTTPS host is redirected to the
|
||||
same host on HTTPS, on the status page's port and the Manager's; the status page stays on plain
|
||||
HTTP by any other address, and `/pki/` stays on plain HTTP. A certificate whose names or addresses
|
||||
differ from the current ones is made or issued again at the next setup, so a changed DHCP address
|
||||
is followed. As Caddy always listens, the firewall is always set up.
|
||||
|
||||
Consequences: A browser warns about a self-signed certificate, or one of the server's PKI, until
|
||||
its user trusts it or the root; one reached by address warns unless `https.ip_sans` is on. A server
|
||||
whose addresses change gets a new certificate at each change while `https.ip_sans` is on. Avahi is
|
||||
a dependency, running only while there is no FQDN; it sends its announcements on every interface,
|
||||
and the firewall lets queries in on the internal side only.
|
||||
+1442
File diff suppressed because it is too large.
Load diff
+4
-2
@@ -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
@@ -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
|
||||
|
||||
@@ -75,7 +75,6 @@ linux-manager linux-manager/internal_interface string eth1
|
||||
linux-manager linux-manager/int_addr string 10.1.1.4
|
||||
linux-manager linux-manager/int_gateway_ip string 10.1.1.1
|
||||
linux-manager linux-manager/local_fqdn string router.example.com
|
||||
linux-manager linux-manager/https_enabled boolean true
|
||||
linux-manager linux-manager/local_cidrs string 10.0.0.0/24
|
||||
linux-manager linux-manager/remote_addrs string peer.example.net
|
||||
linux-manager linux-manager/remote_id string peer.example.net
|
||||
@@ -146,12 +145,12 @@ must have the type shown below; an unknown section or setting is an error.
|
||||
| `web` | `log_files` | list | | Absolute paths of the log files `/logs` shows, at most 32 (see The /logs API) |
|
||||
| `web` | `shell_auth_timeout` | integer | `15` | Minutes after the last use of a shell in which a new shell opens without signing in again, 0 (always sign in) to 1440 |
|
||||
| `ssh` | `ldap_login` | boolean | `false` | sshd accepts the directory password of the console accounts in the directory (see Console login and SSH) |
|
||||
| `https` | `enabled` | boolean | `true` | Caddy serves the status web service and the Manager over HTTPS for `wan.local_fqdn` |
|
||||
| `https` | `email` | string | | The e-mail address of the ACME account |
|
||||
| `https` | `web_port` | integer | `7444` | HTTPS port of the status web service |
|
||||
| `https` | `manager_port` | integer | `7443` | HTTPS port of the Manager |
|
||||
| `https` | `disable_auto_redirect` | boolean | `false` | The Manager answers on its plain HTTP port instead of redirecting there to its HTTPS address while `enabled` is `true`; the status page never redirects |
|
||||
| `https` | `certificate` | string | `self-signed` | Where the certificate of `wan.local_fqdn` comes from: `self-signed`, `ca`, `acme` or `external`; empty in a new installation's file, for its first setup to choose `ca` or `self-signed` and write it here (see HTTPS) |
|
||||
| `https` | `disable_auto_redirect` | boolean | `false` | The status page and the Manager answer by their HTTPS names on their plain HTTP ports instead of redirecting there to HTTPS (see HTTPS) |
|
||||
| `https` | `ip_sans` | boolean | `false` | The self-signed certificate and the one of the Servers Issuing CA also name the server's addresses, so HTTPS is reached by address too (see HTTPS) |
|
||||
| `https` | `certificate` | string | `self-signed` | Where the certificate of the HTTPS names comes from: `self-signed`, `ca`, `acme` or `external`; empty in a new installation's file, or absent before the first successful setup, for its first setup to choose `ca` or `self-signed` and write it here (see HTTPS) |
|
||||
| `https` | `self_signed_days` | integer | `365` | Days the self-signed certificate is valid, 1 to 3650 |
|
||||
| `https` | `acme_provider` | string | `letsencrypt` | The ACME CA of the server and of the web sites with `tls` `acme`: `letsencrypt`, `zerossl` or `custom` (see HTTPS) |
|
||||
| `https` | `acme_url` | string | | The `https://` ACME directory URL of `custom` |
|
||||
@@ -159,10 +158,10 @@ must have the type shown below; an unknown section or setting is an error.
|
||||
| `https` | `acme_eab_mac_key` | string | | The EAB MAC key of `custom` |
|
||||
| `https` | `zerossl_api_key` | string | | The ZeroSSL API key; without it the EAB credentials come from `email` |
|
||||
| `https` | `acme_staging` | boolean | `false` | With `letsencrypt`, Caddy takes its certificates from Let's Encrypt's staging environment, whose certificates no browser trusts and whose rate limits are higher, for routers rebuilt often (see HTTPS) |
|
||||
| `oidc` | `enabled` | boolean | `false` | The OpenID Provider at the status web service's HTTPS site, which needs `web.enabled`, `https.enabled` and `wan.local_fqdn` (see OpenID Provider) |
|
||||
| `oidc` | `enabled` | boolean | `false` | The OpenID Provider at the status web service's HTTPS site, which needs `web.enabled` (see OpenID Provider) |
|
||||
| `sites` | `enabled` | boolean | `false` | Caddy serves the web sites (see Web sites) |
|
||||
| `sites` | `upload_max_mb` | integer | `512` | The largest upload of a site's file or zip archive, in MiB, 1 to 10240 |
|
||||
| `sites` | `webdav` | boolean | `false` | WebDAV of the sites' folders, which needs `https.enabled` and `wan.local_fqdn` (see WebDAV) |
|
||||
| `sites` | `webdav` | boolean | `false` | WebDAV of the sites' folders, served over HTTPS for the HTTPS names (see WebDAV) |
|
||||
| `sites` | `webdav_port` | integer | `7445` | HTTPS port of WebDAV |
|
||||
| `dns` | `enabled` | boolean | `false` | The primary name server of the server's domains, `wan.local_fqdn`, which must then be a DNS name (see Name server) |
|
||||
| `dns` | `secondary` | string | | The optional secondary name server of every domain, a host name other than `wan.local_fqdn`; it may transfer the domains; empty, `wan.local_fqdn` is the only name server |
|
||||
@@ -176,7 +175,6 @@ must have the type shown below; an unknown section or setting is an error.
|
||||
| `pki` | `key` | string | `rsa-4096` | Key of the root and the issuing CAs: `rsa-2048`, `rsa-3072`, `rsa-4096`, `ec-p256` or `ec-p384` |
|
||||
| `pki` | `crl_days` | integer | `7` | Days the CRLs of the issuing CAs are valid |
|
||||
| `pki` | `root_crl_days` | integer | `180` | Days the root CRL is valid, when the server signs it |
|
||||
| `pki` | `publish` | list | `http` | Where the CA certificates and CRLs are published: `http`, `http-80`, `https`, `https-default` (see Certificates) |
|
||||
| `pki` | `p2s_name` | string | `Linux Manager VPN CA` | Common name of the P2S issuing CA; fixed once the CA exists, from when the VPN is first on |
|
||||
| `pki` | `s2s_name` | string | `Linux Manager Site-to-Site CA` | Common name of the site-to-site issuing CA; fixed once the CA exists, from when the router is first on |
|
||||
| `pki` | `servers_name` | string | `Linux Manager Servers CA` | Common name of the Servers Issuing CA; fixed by the first setup, which creates the CA |
|
||||
@@ -186,7 +184,7 @@ must have the type shown below; an unknown section or setting is an error.
|
||||
| `metrics` | `enabled` | boolean | `true` | The metrics service: collection, history and `/metrics` |
|
||||
| `metrics` | `listen` | string | `internal` | The interfaces the firewall opens `metrics.port` on: `internal`, `external` or `both` |
|
||||
| `metrics` | `port` | integer | `9464` | TCP port of `/metrics`, served by Caddy over plain HTTP |
|
||||
| `metrics` | `https_port` | integer | `9465` | HTTPS port of `/metrics`, served by Caddy while `https.enabled` is true |
|
||||
| `metrics` | `https_port` | integer | `9465` | HTTPS port of `/metrics`, served by Caddy |
|
||||
| `metrics` | `service_account` | string | `metrics` | The service account `/metrics` takes, which `linux-manager-setup` adds and keeps |
|
||||
| `metrics` | `otlp_endpoint` | string | | An OTLP/HTTP URL the metrics are pushed to every minute, for example `https://collector.example.com:4318/v1/metrics` |
|
||||
| `metrics` | `otlp_username` | string | | The user name of HTTP Basic authentication at the OTLP endpoint |
|
||||
@@ -497,14 +495,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
|
||||
@@ -616,21 +637,22 @@ certificate is revoked by removing the user, and an issuing CA by removing it fr
|
||||
|
||||
### Published certificates and CRLs
|
||||
|
||||
Every certificate names its issuer's certificate (AIA) and CRL (CRL distribution point) at each
|
||||
endpoint of `pki.publish`, in that order. They are served, without authentication, as DER at
|
||||
`/pki/<name>.crt` and `/pki/<name>.crl`, the root as `root`, from copies in
|
||||
`/var/lib/linux-manager/pki-publish`:
|
||||
Caddy serves the CA certificates and CRLs, without authentication, as DER at `/pki/<name>.crt`
|
||||
(`application/pkix-cert`) and `/pki/<name>.crl` (`application/pkix-crl`), the root as `root`, from
|
||||
copies in `/var/lib/linux-manager/pki-publish`, over plain HTTP on `web.port` while `web.enabled`
|
||||
and on the Manager's port, and while HTTPS is on also on `https.manager_port` and, while
|
||||
`web.enabled` or an issuing CA has ACME, on `https.web_port`. On the Manager's plain HTTP port,
|
||||
`/pki/` is answered before the redirect to HTTPS.
|
||||
|
||||
| Endpoint | URL | Served by |
|
||||
|---|---|---|
|
||||
| `http` | `http://<wan.local_fqdn>:<web.port>/pki/` | the status web service; needs `web.enabled` |
|
||||
| `http-80` | `http://<wan.local_fqdn>/pki/` | Caddy, on port 80, open on both interfaces; needs `https.enabled` |
|
||||
| `https` | `https://<wan.local_fqdn>:<https.web_port>/pki/` | Caddy; needs `https.enabled` |
|
||||
| `https-default` | `https://<wan.local_fqdn>/pki/` | Caddy, on port 443, open on both interfaces; needs `https.enabled` |
|
||||
Every certificate names its issuer's certificate (AIA) and CRL (CRL distribution point) at the
|
||||
plain HTTP URLs, in this order:
|
||||
|
||||
The URLs are written into a certificate when it is signed, so a change of `pki.publish` or of the
|
||||
names applies to the certificates signed afterwards. An empty `pki.publish` leaves the extensions
|
||||
out.
|
||||
- `http://<wan.local_fqdn>:<web.port>/pki/`, while `web.enabled`;
|
||||
- `http://<wan.local_fqdn>:<Manager port>/pki/`.
|
||||
|
||||
The URLs are written into a certificate when it is signed, so a change of the ports or of
|
||||
`wan.local_fqdn` applies to the certificates signed afterwards. Without `wan.local_fqdn` the
|
||||
extensions are left out.
|
||||
|
||||
The CRLs of the issuing CAs are valid for `pki.crl_days`, and the root CRL, when the server signs
|
||||
it, for `pki.root_crl_days`. A CRL is signed again at every revocation and, once half of its
|
||||
@@ -729,8 +751,8 @@ setup code. A retired issuing CA is revoked in Simple CA, where the server canno
|
||||
|
||||
### ACME server
|
||||
|
||||
A general-purpose CA with `"acme": true` backs an ACME server of Caddy, while `https.enabled`, at
|
||||
`https://<wan.local_fqdn>:<https.web_port>/acme/<name>/directory`, so servers get and renew
|
||||
A general-purpose CA with `"acme": true` backs an ACME server of Caddy, at
|
||||
`https://<HTTPS name>:<https.web_port>/acme/<name>/directory`, so servers get and renew
|
||||
certificates with any ACME client:
|
||||
|
||||
```sh
|
||||
@@ -773,8 +795,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
|
||||
@@ -1599,31 +1623,45 @@ and the facts for `/config` from `/run/linux-manager/web.json` (readable by root
|
||||
Caddy, a dependency of the package, serves every HTTP and HTTPS port of the server's services; the
|
||||
services listen on `127.0.0.1` only. Over plain HTTP it serves the status web service on
|
||||
`web.port` (7081 by default), the Manager on its `port` (7080), and while metrics are enabled the
|
||||
metrics service on `metrics.port` (9464). While `https.enabled` is `true` and `wan.local_fqdn` is
|
||||
set, it also serves the status web service on `https.web_port` (7444), the Manager on
|
||||
`https.manager_port` (7443), and while metrics are enabled the metrics service on
|
||||
`metrics.https_port` (9465), all for `wan.local_fqdn`.
|
||||
metrics service on `metrics.port` (9464). HTTPS is always on: Caddy also serves the status web
|
||||
service on `https.web_port` (7444), the Manager on `https.manager_port` (7443), and while metrics
|
||||
are enabled the metrics service on `metrics.https_port` (9465), all for the HTTPS names:
|
||||
|
||||
The installer asks whether to serve over HTTPS (`https_enabled`) and, with HTTPS, whether to keep
|
||||
the Manager on plain HTTP (`https_disable_auto_redirect`). While HTTPS is on, Caddy answers the
|
||||
Manager's plain HTTP port with a redirect (308) to the same path at
|
||||
`https://<wan.local_fqdn>:<https.manager_port>`, unless `https.disable_auto_redirect` is `true`.
|
||||
The status page never redirects and stays available over plain HTTP on `web.port` whether HTTPS
|
||||
is on or not.
|
||||
- `wan.local_fqdn` alone, when it is set;
|
||||
- without it, the host name and `<host name>.local`, which Avahi announces with mDNS on the
|
||||
internal side (the external interface of a server with one), where the firewall opens UDP 5353;
|
||||
Avahi is stopped while `wan.local_fqdn` is set.
|
||||
|
||||
With `https.ip_sans`, the self-signed certificate and the one of the Servers Issuing CA also name
|
||||
the server's addresses, those of its interfaces and `wan.public_address`, without link-local ones,
|
||||
and Caddy serves HTTPS on them too. It is off by default, as a server is rarely reached by address;
|
||||
a server that is the first device of a network can then be set up over HTTPS by address, once its
|
||||
certificate is accepted. A client without SNI gets the certificate of the first HTTPS name. An ACME
|
||||
certificate names `wan.local_fqdn` only, which `https.certificate` `acme` needs.
|
||||
|
||||
The installer asks whether to keep plain HTTP (`https_disable_auto_redirect`). Unless
|
||||
`https.disable_auto_redirect` is `true`, Caddy answers a plain HTTP request for an HTTPS name with a
|
||||
redirect (308) to the same host and path on HTTPS: on `web.port` to `https.web_port`, on the
|
||||
Manager's port to `https.manager_port`; with `https.ip_sans`, a request by address is an HTTPS
|
||||
host too. The status page stays available over plain HTTP by any other address; every other
|
||||
request on the Manager's port is redirected to the first HTTPS name. `/pki/` stays on plain HTTP
|
||||
on both ports. With the redirect off, both answer over plain HTTP by name and by address.
|
||||
|
||||
### The server's certificate
|
||||
|
||||
`https.certificate` says where the certificate of `wan.local_fqdn` comes from; it is `self-signed`
|
||||
when the file does not set it, and ACME only when it is set to `acme`. The file a new installation
|
||||
`https.certificate` says where the certificate of the HTTPS names comes from; it is `self-signed`
|
||||
when the file of a server already set up does not set it, and ACME only when it is set to `acme`. The file a new installation
|
||||
writes has it empty, and that installation's first setup chooses it and writes it into the file:
|
||||
`ca` when the root CA and the Servers Issuing CA are available, as with a root the server creates,
|
||||
else `self-signed`, as with an offline root, a Simple CA root that has not signed yet, or a
|
||||
directory that cannot be reached. A source chosen later, in the Manager or the file, stays.
|
||||
directory that cannot be reached. Until a setup run has succeeded, a file that does not set it,
|
||||
such as one written in place of the installer's, gets the same choice. A source chosen later, in
|
||||
the Manager or the file, stays.
|
||||
|
||||
| Source | The certificate |
|
||||
|---|---|
|
||||
| `acme` | obtained and renewed by Caddy from the ACME CA of `https.acme_provider`, with the HTTP challenge, so `wan.local_fqdn` resolves to the server's public address and port 80 is reachable from the internet; kept in `/var/lib/caddy` |
|
||||
| `self-signed` (the default) | made by the server, valid for `https.self_signed_days`, and made again when a third of it is left or `wan.local_fqdn` changes |
|
||||
| `self-signed` (the default) | made by the server, valid for `https.self_signed_days`, and made again when a third of it is left or its names or addresses change |
|
||||
| `ca` | issued and renewed by the Servers Issuing CA, `servers`, of the server's PKI (see Certificates), with the template `mtls` |
|
||||
| `external` | another CA's certificate, imported, from a CSR the server makes or as a PFX file |
|
||||
|
||||
@@ -1675,9 +1713,8 @@ reloads it when the file changes.
|
||||
Caddy listens on every address, and the firewall decides who reaches it: `web.port` is open on the
|
||||
interfaces `web.listen` names, the Manager's port on those of its `listen`, and `metrics.port` on
|
||||
those of `metrics.listen`, where `internal` is the external interface without the router. Port
|
||||
80 is open on the external interface while ACME needs it, the HTTPS ports on the internal and the
|
||||
external interface, and ports 80 and 443 on both when `pki.publish` has `http-80` and
|
||||
`https-default`, on which Caddy serves only the CA files (see Certificates).
|
||||
80 is open on the external interface while ACME needs it, and the HTTPS ports on the internal and
|
||||
the external interface.
|
||||
|
||||
Caddy calls the services on `127.0.0.1`: the status web service on port 7091, the Manager on
|
||||
7090, the metrics service on 9474 and WebDAV on 7446, and passes the client's address in
|
||||
@@ -1700,9 +1737,9 @@ Caddy is a dependency of the package, the `caddy` package of the Ubuntu archive,
|
||||
|
||||
While `oidc.enabled` is `true`, the status web service is an OpenID Provider (OpenID Connect
|
||||
Core 1.0) for the users of the directory. Its issuer is the web service's HTTPS site,
|
||||
`https://<wan.local_fqdn>:<https.web_port>`, without the port when it is 443; the web service
|
||||
answers it only on `127.0.0.1`, where Caddy passes the requests, so the provider is never reached
|
||||
over plain HTTP. The setting needs `web.enabled`, `https.enabled` and `wan.local_fqdn`.
|
||||
`https://<HTTPS name>:<https.web_port>`, the first HTTPS name, without the port when it is 443; the
|
||||
web service answers it only on `127.0.0.1`, where Caddy passes the requests, so the provider is
|
||||
never reached over plain HTTP. The setting needs `web.enabled`.
|
||||
|
||||
```sh
|
||||
linux-manager-config-edit set --restart oidc.enabled true
|
||||
@@ -2215,10 +2252,9 @@ the Overview, Metrics, Logs, Backup and System tabs), Identities (`/user-manager
|
||||
Accounts tabs), Connectivity (`/site-to-site-manager`: the Status, Network and Connections tabs), Remote
|
||||
Access (`/remote-access-manager`: the IKEv2, OpenVPN and WireGuard tabs), Certificates
|
||||
(`/ca-manager`), Web Sites (`/sites-manager`: the Sites and Files tabs), DNS (`/dns-manager`, while the name
|
||||
server is on) and Docker (`/docker-manager`) with the page menu at the
|
||||
right end of the header, a button naming the page shown. The button with the signed-in user's
|
||||
name, left of Sign out, opens the account page, and the terminal icon left of it the Shell
|
||||
(`/shell`); pressed on its page, each returns to the page it was opened from.
|
||||
server is on), Docker (`/docker-manager`) and Shell (`/shell`) with the page menu at the right end
|
||||
of the header, a button naming the page shown. The button with the signed-in user's name, left of
|
||||
Sign out, opens the account page; pressed on it, it returns to the page it was opened from.
|
||||
|
||||
- **Help** (the question mark in the header between the theme switcher and the page menu, for every
|
||||
signed-in user): a panel on the right, under
|
||||
@@ -2233,8 +2269,8 @@ name, left of Sign out, opens the account page, and the terminal icon left of it
|
||||
on their own, kept in the browser's localStorage, so each browser has its own. Each tab reads
|
||||
manually, or every 5, 10 or 30 seconds, 1, 5 or 15 minutes; the Overview tab every 10 seconds and
|
||||
the Metrics tab every minute by default. Manual reads when the tab opens and on Refresh. **Open
|
||||
the shell in a new tab**, off by default, makes the shell button open the shell in a tab of its
|
||||
own, which stays open while the first tab opens other pages. A change applies at once, also in
|
||||
the shell in a new tab**, off by default, makes the page menu open the Shell page in a tab of
|
||||
its own, which stays open while the first tab opens other pages. A change applies at once, also in
|
||||
the browser's other tabs; Defaults sets them back.
|
||||
|
||||
- **Account** (`/user`): the Account and the Passkeys panel side by side, with One-time passwords
|
||||
@@ -2413,7 +2449,7 @@ name, left of Sign out, opens the account page, and the terminal icon left of it
|
||||
the ports exposed on the external interface and the rules of the `LINUX-MANAGER-DOCKER` chain,
|
||||
from the server's `/status/full` and `/config`. The page menu leaves the page out while
|
||||
`/config` says Docker is not installed, and the page itself then says so.
|
||||
- **Shell** (`/shell`, the terminal icon in the header): a login shell on the server in xterm.js, the terminal of VS Code, as the
|
||||
- **Shell** (`/shell`, in the page menu of administrators): a login shell on the server in xterm.js, the terminal of VS Code, as the
|
||||
signed-in user's console account, the user's own LDAP POSIX account or a local account. Opening
|
||||
it asks for the password and the code again, or Open with a passkey takes one of the user's
|
||||
passkeys, unlocked with the device's PIN or biometrics, unless the user used a shell within the
|
||||
@@ -2422,7 +2458,7 @@ name, left of Sign out, opens the account page, and the terminal icon left of it
|
||||
on the server with `linux-manager-config-edit`, and closes it after `web.shell_idle_minutes` without a
|
||||
keystroke; the page then shows the reason and keeps the terminal readable.
|
||||
- **Editor:** `lme FILE...` (`linux-manager-editor`) in the shell opens the files in a Monaco editor on the page, one tab per file, and returns at once. The server names each file in a text message of the shell's WebSocket, and the page reads and saves it through `/api/shell/editor/<session>/<id>`, as the console account. Saves have a body limit of 2 MiB plus 64 KiB, for a file of up to 1 MiB escaped in JSON; other calls keep 64 KiB.
|
||||
- **Editor icon:** while a file is open, an icon left of the shell icon switches the page between the terminal and the editor, and the shell keeps running. A button left of Save shows or hides the minimap, remembered by the browser. Save or Ctrl+S writes the file; a file changed on the server since it was read offers Reload or Overwrite. Closing a tab with unsaved changes asks first, and the icon goes when the last tab closes or the shell ends.
|
||||
- **Editor icon:** while a file is open, an icon left of the user's name in the header switches the page between the terminal and the editor, and the shell keeps running. A button left of Save shows or hides the minimap, remembered by the browser. Save or Ctrl+S writes the file; a file changed on the server since it was read offers Reload or Overwrite. Closing a tab with unsaved changes asks first, and the icon goes when the last tab closes or the shell ends.
|
||||
- **Loading:** Monaco is bundled with the page, without its language services, and loaded only when the first file opens.
|
||||
- **Backup**: the server's backups, from its `/backup`:
|
||||
- **Settings:** whether scheduled backups run, the schedule (hourly, daily or weekly), the target and whether the metrics database is included. For a local folder it also shows the folder, the archives kept and the cloud copy with rclone; for a Proxmox Backup Server, the repository, whether the token secret is set, the fingerprint, the namespace and the encryption key file.
|
||||
@@ -2543,9 +2579,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 +2613,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 +2671,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 +2681,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.
|
||||
@@ -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
@@ -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
@@ -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)
|
||||
|
||||
@@ -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
@@ -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
@@ -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')
|
||||
|
||||
|
||||
+53
-37
@@ -1,34 +1,37 @@
|
||||
#!/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, dev.json by default), whose @ETH0@ is the
|
||||
interface of its default route, @CIDR0@ its network, @FQDN@ --fqdn (LXD_DEV_FQDN, lm-dev.test by default), and @PSK@ a
|
||||
generated key; the Manager and the status web service answer HTTPS for that name, which has to resolve to the
|
||||
listen address. 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.
|
||||
|
||||
The VM's leased address is pinned on its NIC, and ports 7080 and 7081 of a listen address lead to
|
||||
the same ports of the VM, and port 2222 to its SSH port. In a test project the listen address is a
|
||||
The VM's leased address is pinned on its NIC, and ports 7080, 7081, 7443 and 7444 of a listen address
|
||||
lead to the same ports of the VM, and port 2222 to its SSH port. In a test project the listen address is a
|
||||
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,36 +39,42 @@ 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))
|
||||
# The listen port and the VM port of each forward or proxy: the Manager and the status web service over HTTP and
|
||||
# HTTPS, and SSH.
|
||||
PORTS = ((7080, 7080), (7081, 7081), (7443, 7443), (7444, 7444), (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('--config', default='dev.json',
|
||||
help='the configuration from tests/remote/configs/ (default dev.json)')
|
||||
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('--fqdn', default=setting('LXD_DEV_FQDN', 'lm-dev.test'),
|
||||
help='the name of the VM in its configuration, @FQDN@ (LXD_DEV_FQDN, default lm-dev.test)')
|
||||
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 +83,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 +117,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 +127,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}')
|
||||
@@ -219,7 +233,8 @@ def main():
|
||||
sys.exit(f'the package did not install; see {log}')
|
||||
|
||||
# Apply the configuration twice, as the server's certificates follow the first run.
|
||||
text = config.read_text(encoding='utf-8').replace('@ETH0@', nic).replace('@CIDR0@', str(interface.network))
|
||||
text = config.read_text(encoding='utf-8').replace('@ETH0@', nic).replace('@CIDR0@', str(interface.network))\
|
||||
.replace('@FQDN@', args.fqdn)
|
||||
problem = hand_over(args.remote, args.project, args.vm, vault, 'config', text.replace('@PSK@', psk),
|
||||
'/etc/linux-manager/linux-manager.json', '0600')
|
||||
if problem:
|
||||
@@ -234,11 +249,12 @@ 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'manager: http://{args.listen}:7080/ status: http://{args.listen}:7081/ ssh: {args.listen} port 2222')
|
||||
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: https://{args.fqdn}:7443/ status: https://{args.fqdn}:7444/ and http://{args.listen}:7081/ '
|
||||
f'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
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/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 argparse
|
||||
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():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0], allow_abbrev=False,
|
||||
usage='%(prog)s [-h] [CONTAINER BUILD OPTIONS]',
|
||||
epilog="the other options are passed to the container runtime's build")
|
||||
_, options = parser.parse_known_args()
|
||||
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, *options, '.']
|
||||
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())
|
||||
@@ -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
@@ -67,7 +67,6 @@ fi
|
||||
db_go || true
|
||||
|
||||
db_input high linux-manager/local_fqdn || true
|
||||
db_input high linux-manager/https_enabled || true
|
||||
if [ "$ROUTER" = "true" ] || [ "$VPN" = "true" ]; then
|
||||
db_input high linux-manager/local_cidrs || true
|
||||
fi
|
||||
@@ -85,11 +84,8 @@ if [ "$VPN" = "true" ]; then
|
||||
fi
|
||||
db_go || true
|
||||
|
||||
db_get linux-manager/https_enabled
|
||||
if [ "$RET" = "true" ]; then
|
||||
db_input high linux-manager/https_disable_auto_redirect || true
|
||||
db_go || true
|
||||
fi
|
||||
db_input high linux-manager/https_disable_auto_redirect || true
|
||||
db_go || true
|
||||
|
||||
db_get linux-manager/pki_root
|
||||
if [ "$RET" = "local" ]; then
|
||||
|
||||
@@ -25,6 +25,7 @@ Depends: ${misc:Depends},
|
||||
python3-prometheus-client,
|
||||
python3-requests,
|
||||
caddy,
|
||||
avahi-daemon,
|
||||
postgresql,
|
||||
slapd,
|
||||
nslcd,
|
||||
|
||||
@@ -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/
|
||||
|
||||
@@ -24,7 +24,6 @@ case "$1" in
|
||||
answer linux-manager/external_interface; LINUX_MANAGER_EXTERNAL_INTERFACE="$ANSWER"
|
||||
answer linux-manager/internal_interface; LINUX_MANAGER_INTERNAL_INTERFACE="$ANSWER"
|
||||
answer linux-manager/local_fqdn; LINUX_MANAGER_LOCAL_FQDN="$ANSWER"
|
||||
answer linux-manager/https_enabled; LINUX_MANAGER_HTTPS_ENABLED="$ANSWER"
|
||||
answer linux-manager/https_disable_auto_redirect; LINUX_MANAGER_HTTPS_DISABLE_AUTO_REDIRECT="$ANSWER"
|
||||
answer linux-manager/local_id_mode; LINUX_MANAGER_LOCAL_ID_MODE="$ANSWER"
|
||||
answer linux-manager/local_cidrs; LINUX_MANAGER_LOCAL_CIDRS="$ANSWER"
|
||||
@@ -46,7 +45,7 @@ case "$1" in
|
||||
LINUX_MANAGER_ROUTER_ENABLED LINUX_MANAGER_VPN_ENABLED \
|
||||
LINUX_MANAGER_EXTERNAL_INTERFACE \
|
||||
LINUX_MANAGER_INTERNAL_INTERFACE LINUX_MANAGER_LOCAL_FQDN \
|
||||
LINUX_MANAGER_HTTPS_ENABLED LINUX_MANAGER_HTTPS_DISABLE_AUTO_REDIRECT \
|
||||
LINUX_MANAGER_HTTPS_DISABLE_AUTO_REDIRECT \
|
||||
LINUX_MANAGER_LOCAL_ID_MODE LINUX_MANAGER_LOCAL_CIDRS \
|
||||
LINUX_MANAGER_INT_GATEWAY_IP \
|
||||
LINUX_MANAGER_REMOTE_ADDRS LINUX_MANAGER_REMOTE_ID \
|
||||
|
||||
@@ -95,22 +95,15 @@ Description: Local router FQDN:
|
||||
router.example.com). Used as the IKEv2 server identity and
|
||||
certificate common name.
|
||||
|
||||
Template: linux-manager/https_enabled
|
||||
Type: boolean
|
||||
Default: true
|
||||
Description: Serve the status page and the Manager over HTTPS?
|
||||
If enabled, Caddy serves the status page and the Manager over HTTPS for the
|
||||
router FQDN, with a certificate of the Servers Issuing CA when the server
|
||||
creates its root CA, and a self-signed one otherwise. The status page stays
|
||||
available over plain HTTP either way.
|
||||
|
||||
Template: linux-manager/https_disable_auto_redirect
|
||||
Type: boolean
|
||||
Default: false
|
||||
Description: Keep the Manager available over plain HTTP?
|
||||
If enabled, the Manager answers on its plain HTTP port. Otherwise, while
|
||||
HTTPS is on, it redirects there to its HTTPS address. The status page never
|
||||
redirects.
|
||||
Description: Keep the status page and the Manager available over plain HTTP?
|
||||
Caddy always serves the status page and the Manager over HTTPS, for the
|
||||
router FQDN or, without one, for the host name and <host name>.local. If
|
||||
enabled, both also answer on their plain HTTP ports by name. Otherwise a
|
||||
request by name on those ports is redirected to HTTPS; the status page stays
|
||||
available over plain HTTP by address.
|
||||
|
||||
Template: linux-manager/local_id_mode
|
||||
Type: select
|
||||
|
||||
@@ -43,7 +43,6 @@ ANSWERS = {
|
||||
'LINUX_MANAGER_EXTERNAL_INTERFACE': (('interfaces', 'external'),),
|
||||
'LINUX_MANAGER_INTERNAL_INTERFACE': (('interfaces', 'internal'),),
|
||||
'LINUX_MANAGER_LOCAL_FQDN': (('wan', 'local_fqdn'),),
|
||||
'LINUX_MANAGER_HTTPS_ENABLED': (('https', 'enabled'),),
|
||||
'LINUX_MANAGER_HTTPS_DISABLE_AUTO_REDIRECT': (('https', 'disable_auto_redirect'),),
|
||||
'LINUX_MANAGER_LOCAL_ID_MODE': ((*FIRST, 'local_id_mode'),),
|
||||
'LINUX_MANAGER_LOCAL_CIDRS': (('local', 'cidrs'), (*FIRST, 'local_cidrs')),
|
||||
|
||||
@@ -12,6 +12,7 @@ import os
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -79,7 +80,7 @@ SCHEMA = {
|
||||
'status_content': 'basic', 'shell': False, 'shell_idle_minutes': 15, 'shell_auth_timeout': 15,
|
||||
'log_files': []},
|
||||
'ssh': {'ldap_login': False},
|
||||
'https': {'enabled': True, 'email': '', 'web_port': 7444, 'manager_port': 7443,
|
||||
'https': {'email': '', 'web_port': 7444, 'manager_port': 7443, 'ip_sans': False,
|
||||
'disable_auto_redirect': False, 'acme_staging': False, 'certificate': 'self-signed', 'self_signed_days': 365,
|
||||
'acme_provider': 'letsencrypt', 'acme_url': '', 'acme_eab_key_id': '', 'acme_eab_mac_key': '',
|
||||
'zerossl_api_key': ''},
|
||||
@@ -87,7 +88,7 @@ SCHEMA = {
|
||||
'sites': {'enabled': False, 'upload_max_mb': 512, 'webdav': False, 'webdav_port': 7445},
|
||||
'dns': {'enabled': False, 'secondary': '', 'listen': 'external', 'ttl': 300},
|
||||
'pki': {'root_name': 'Linux Manager Root CA', 'root_days': 7300, 'ca_days': 3650, 'key': 'rsa-4096',
|
||||
'crl_days': 7, 'root_crl_days': 180, 'publish': ['http'], 'p2s_name': 'Linux Manager VPN CA',
|
||||
'crl_days': 7, 'root_crl_days': 180, 'p2s_name': 'Linux Manager VPN CA',
|
||||
's2s_name': 'Linux Manager Site-to-Site CA', 'servers_name': 'Linux Manager Servers CA',
|
||||
'issuing_cas': {}, 'templates': {},
|
||||
'extended_key_usages': {}, 'root': 'local', 'simple_ca_url': ''},
|
||||
@@ -148,7 +149,7 @@ PBS_NAMESPACE = re.compile(r'^[A-Za-z0-9_][A-Za-z0-9._-]*(/[A-Za-z0-9_][A-Za-z0-
|
||||
#: The port of Let's Encrypt's HTTP challenge, which Caddy answers while HTTPS is on.
|
||||
ACME_HTTP_PORT = 80
|
||||
|
||||
#: The default port of HTTPS, where Caddy publishes the CA files when pki.publish has https-default.
|
||||
#: The default port of HTTPS.
|
||||
HTTPS_DEFAULT_PORT = 443
|
||||
|
||||
#: The most files web.log_files lists.
|
||||
@@ -171,8 +172,9 @@ COMPONENTS = {
|
||||
UPLOAD_MAX_MB = 10240
|
||||
|
||||
#: Settings that no longer exist, section -> options, left out when the file is read so that a file of an earlier
|
||||
#: version loads: the name server is wan.local_fqdn and a site chooses the address of its records.
|
||||
RETIRED = {'dns': ('nameserver', 'addresses')}
|
||||
#: version loads: the name server is wan.local_fqdn, a site chooses the address of its records, and the CA certificates
|
||||
#: and CRLs are always published, and HTTPS is always on.
|
||||
RETIRED = {'dns': ('nameserver', 'addresses'), 'pki': ('publish',), 'https': ('enabled',)}
|
||||
|
||||
#: The shortest and the longest dns.ttl, in seconds.
|
||||
DNS_TTL_RANGE = (60, 86400)
|
||||
@@ -212,9 +214,6 @@ PKI_KEYS = ('rsa-2048', 'rsa-3072', 'rsa-4096', 'ec-p256', 'ec-p384')
|
||||
#: Where the root CA comes from, pki.root: the server creates it, an offline CA, or a Simple CA service.
|
||||
PKI_ROOTS = ('local', 'offline', 'simple-ca')
|
||||
|
||||
#: Where the CA certificates and CRLs are published, pki.publish, as the URLs in the certificates list them.
|
||||
PKI_PUBLISH = ('http', 'http-80', 'https', 'https-default')
|
||||
|
||||
#: The key usages a template may give, as the arguments of cryptography's KeyUsage.
|
||||
KEY_USAGES = ('digital_signature', 'content_commitment', 'key_encipherment', 'data_encipherment', 'key_agreement')
|
||||
|
||||
@@ -686,19 +685,16 @@ def validate(cfg):
|
||||
for option in ('email', 'acme_url', 'acme_eab_key_id', 'acme_eab_mac_key', 'zerossl_api_key'):
|
||||
if any(character.isspace() or character in '{}"' for character in _get(cfg, 'https', option)):
|
||||
raise ConfigError(f'https.{option} must not hold spaces, braces or quotes')
|
||||
if _get(cfg, 'https', 'certificate') == 'acme' and not _get(cfg, 'wan', 'local_fqdn'):
|
||||
raise ConfigError('https.certificate: an ACME CA issues the certificate of wan.local_fqdn, which is not set')
|
||||
|
||||
if _get(cfg, 'oidc', 'enabled') and not (_get(cfg, 'web', 'enabled') and _get(cfg, 'https', 'enabled')
|
||||
and _get(cfg, 'wan', 'local_fqdn')):
|
||||
if _get(cfg, 'oidc', 'enabled') and not _get(cfg, 'web', 'enabled'):
|
||||
raise ConfigError('oidc.enabled: the OpenID Provider is the web service served by Caddy at '
|
||||
'https://<wan.local_fqdn>:<https.web_port>, which needs web.enabled, https.enabled and '
|
||||
'wan.local_fqdn')
|
||||
'https://<HTTPS name>:<https.web_port>, which needs web.enabled')
|
||||
|
||||
upload_max = _get(cfg, 'sites', 'upload_max_mb')
|
||||
if not 1 <= upload_max <= UPLOAD_MAX_MB:
|
||||
raise ConfigError(f'sites.upload_max_mb: {upload_max} is not between 1 and {UPLOAD_MAX_MB}')
|
||||
if _get(cfg, 'sites', 'webdav') and not (_get(cfg, 'https', 'enabled') and _get(cfg, 'wan', 'local_fqdn')):
|
||||
raise ConfigError('sites.webdav: WebDAV is served by Caddy at https://<wan.local_fqdn>:<sites.webdav_port>, '
|
||||
'which needs https.enabled and wan.local_fqdn')
|
||||
|
||||
_check_address(_get(cfg, 'wan', 'public_address'), 'wan.public_address')
|
||||
dns = cfg['dns']
|
||||
@@ -749,18 +745,6 @@ def validate(cfg):
|
||||
raise ConfigError('pki.simple_ca_url must be an https:// URL without a query or a fragment')
|
||||
if _get(cfg, 'pki', 'key') not in PKI_KEYS:
|
||||
raise ConfigError(f'pki.key: {_get(cfg, "pki", "key")!r} is not one of {", ".join(PKI_KEYS)}')
|
||||
publish = _get_list(cfg, 'pki', 'publish')
|
||||
for item in publish:
|
||||
if item not in PKI_PUBLISH:
|
||||
raise ConfigError(f'pki.publish: {item!r} is not one of {", ".join(PKI_PUBLISH)}')
|
||||
if len(set(publish)) != len(publish):
|
||||
raise ConfigError('pki.publish names an endpoint twice')
|
||||
if publish and not _get(cfg, 'wan', 'local_fqdn'):
|
||||
raise ConfigError('pki.publish needs wan.local_fqdn, the name in the published URLs')
|
||||
if 'http' in publish and not _get(cfg, 'web', 'enabled'):
|
||||
raise ConfigError('pki.publish: http is served by the web service, which needs web.enabled')
|
||||
if set(publish) - {'http'} and not _get(cfg, 'https', 'enabled'):
|
||||
raise ConfigError('pki.publish: http-80, https and https-default are served by Caddy, which needs https.enabled')
|
||||
for name, oid in cfg['pki']['extended_key_usages'].items():
|
||||
prefix = f'pki.extended_key_usages.{name}'
|
||||
if not EKU_NAME.match(name) or name in EXTENDED_KEY_USAGES:
|
||||
@@ -819,8 +803,6 @@ def validate(cfg):
|
||||
raise ConfigError(f'{prefix}.templates: {template!r} is not a template')
|
||||
if template in ROUTER_TEMPLATES:
|
||||
raise ConfigError(f'{prefix}.templates: {template} is issued by the P2S CA only')
|
||||
if authority['acme'] and not _get(cfg, 'https', 'enabled'):
|
||||
raise ConfigError(f'{prefix}.acme: the ACME server is Caddy\'s, which needs https.enabled')
|
||||
|
||||
taken = {web_port: 'web.port', ACME_HTTP_PORT: 'the HTTP challenge',
|
||||
https_ports[0]: 'https.web_port', https_ports[1]: 'https.manager_port'}
|
||||
@@ -833,13 +815,6 @@ def validate(cfg):
|
||||
if port in taken:
|
||||
raise ConfigError(f'{taken[port]}: {port} is the port of {owner}')
|
||||
taken[port] = owner
|
||||
if 'https-default' in publish:
|
||||
if HTTPS_DEFAULT_PORT in taken:
|
||||
raise ConfigError(f'pki.publish: https-default takes port {HTTPS_DEFAULT_PORT}, the port of '
|
||||
f'{taken[HTTPS_DEFAULT_PORT]}')
|
||||
if _get(cfg, 'openvpn', 'protocol') == 'tcp' and _get(cfg, 'openvpn', 'port') == HTTPS_DEFAULT_PORT:
|
||||
raise ConfigError(f'pki.publish: https-default takes port {HTTPS_DEFAULT_PORT}, the port of openvpn.port')
|
||||
taken[HTTPS_DEFAULT_PORT] = 'pki.publish https-default'
|
||||
for section_name, option in (('metrics', 'port'), ('metrics', 'https_port'), ('sites', 'webdav_port')):
|
||||
port = _get(cfg, section_name, option)
|
||||
if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
|
||||
@@ -919,9 +894,7 @@ def validate(cfg):
|
||||
f'docker.exposed_ports: {item!r} is not a port or a port range')
|
||||
weight += 2 if ':' in item else 1
|
||||
first, _, last = item.partition(':')
|
||||
caddy_ports = (web_port, manager_port(), _get(cfg, 'metrics', 'port'),
|
||||
*((ACME_HTTP_PORT, *https_ports, *([HTTPS_DEFAULT_PORT] if 'https-default' in publish else []))
|
||||
if _get(cfg, 'https', 'enabled') else ()))
|
||||
caddy_ports = (web_port, manager_port(), _get(cfg, 'metrics', 'port'), ACME_HTTP_PORT, *https_ports)
|
||||
for port in caddy_ports:
|
||||
if int(first) <= port <= int(last or first):
|
||||
raise ConfigError(f'docker.exposed_ports: {item!r} takes port {port}, which Caddy serves')
|
||||
@@ -963,15 +936,14 @@ def issuing_cas(cfg):
|
||||
|
||||
|
||||
def pki_base_urls(cfg):
|
||||
"""The base URLs, ending in /, under which the CA certificates and CRLs are published, in the order of pki.publish."""
|
||||
"""The plain HTTP base URLs, ending in /, under which Caddy publishes the CA certificates and CRLs and the
|
||||
certificates name them: the status web service's web.port while it is enabled, then the Manager's port; none without
|
||||
wan.local_fqdn."""
|
||||
fqdn = _get(cfg, 'wan', 'local_fqdn')
|
||||
bases = {
|
||||
'http': f'http://{fqdn}:{_get(cfg, "web", "port")}/pki/',
|
||||
'http-80': f'http://{fqdn}/pki/',
|
||||
'https': f'https://{fqdn}:{_get(cfg, "https", "web_port")}/pki/',
|
||||
'https-default': f'https://{fqdn}/pki/',
|
||||
}
|
||||
return [bases[item] for item in _get_list(cfg, 'pki', 'publish') if item in bases] if fqdn else []
|
||||
if not fqdn:
|
||||
return []
|
||||
ports = [*([_get(cfg, 'web', 'port')] if _get(cfg, 'web', 'enabled') else []), manager_port()]
|
||||
return [f'http://{fqdn}:{port}/pki/' for port in ports]
|
||||
|
||||
|
||||
def manager_port():
|
||||
@@ -995,9 +967,10 @@ def manager_listen():
|
||||
|
||||
|
||||
def oidc_issuer(cfg):
|
||||
"""The issuer of the OpenID Provider: the web service's HTTPS site, without the port when it is HTTPS_DEFAULT_PORT."""
|
||||
"""The issuer of the OpenID Provider: the web service's HTTPS site on the first HTTPS name, without the port when it
|
||||
is HTTPS_DEFAULT_PORT."""
|
||||
port = _get(cfg, 'https', 'web_port')
|
||||
return f'https://{_get(cfg, "wan", "local_fqdn")}' + ('' if port == HTTPS_DEFAULT_PORT else f':{port}')
|
||||
return f'https://{https_names(cfg)[0]}' + ('' if port == HTTPS_DEFAULT_PORT else f':{port}')
|
||||
|
||||
|
||||
def resolve_psk(connection, name):
|
||||
@@ -1199,7 +1172,9 @@ def build_context(cfg, public_ip=None):
|
||||
'web_enabled': _get(cfg, 'web', 'enabled'),
|
||||
'web_port': _get(cfg, 'web', 'port'),
|
||||
'web_listen': _get(cfg, 'web', 'listen'),
|
||||
'https_enabled': _get(cfg, 'https', 'enabled'),
|
||||
'https_names': https_names(cfg),
|
||||
'https_ips': https_addresses(cfg, local_addrs, int_addr),
|
||||
'mdns': not local_fqdn,
|
||||
'https_email': _get(cfg, 'https', 'email'),
|
||||
'https_certificate': _get(cfg, 'https', 'certificate'),
|
||||
'https_acme_provider': _get(cfg, 'https', 'acme_provider'),
|
||||
@@ -1211,7 +1186,6 @@ def build_context(cfg, public_ip=None):
|
||||
'https_zerossl_api_key': _get(cfg, 'https', 'zerossl_api_key'),
|
||||
'https_web_port': _get(cfg, 'https', 'web_port'),
|
||||
'https_manager_port': _get(cfg, 'https', 'manager_port'),
|
||||
'pki_publish': _get_list(cfg, 'pki', 'publish'),
|
||||
'pki_acme': [name for name, authority in issuing_cas(cfg).items() if authority['acme']],
|
||||
'metrics_enabled': _get(cfg, 'metrics', 'enabled'),
|
||||
'metrics_port': _get(cfg, 'metrics', 'port'),
|
||||
@@ -1264,9 +1238,30 @@ def vpn_pools(ctx):
|
||||
(wg_ready(ctx), ctx['wg_network'])) if ready]
|
||||
|
||||
|
||||
def https_ready(ctx):
|
||||
"""Caddy serves HTTPS once it is enabled and wan.local_fqdn names the certificate."""
|
||||
return bool(ctx['https_enabled'] and ctx['local_fqdn'])
|
||||
def https_names(cfg):
|
||||
"""The names of the server's HTTPS certificate and sites: wan.local_fqdn alone when it is set, else the host name
|
||||
and <host name>.local, which Avahi announces with mDNS."""
|
||||
fqdn = _get(cfg, 'wan', 'local_fqdn').lower()
|
||||
if fqdn:
|
||||
return [fqdn]
|
||||
host = socket.gethostname().split('.')[0].lower()
|
||||
return [host, f'{host}.local']
|
||||
|
||||
|
||||
def https_addresses(cfg, local_addrs, int_addr):
|
||||
"""The IP addresses of the server's HTTPS certificate and sites while https.ip_sans is on: those of its interfaces
|
||||
and wan.public_address, without link-local ones; [] while it is off."""
|
||||
if not _get(cfg, 'https', 'ip_sans'):
|
||||
return []
|
||||
found = []
|
||||
for value in (*local_addrs, int_addr, _get(cfg, 'wan', 'public_address')):
|
||||
try:
|
||||
address = ipaddress.ip_address(str(value).split('/')[0])
|
||||
except ValueError:
|
||||
continue
|
||||
if not address.is_link_local and str(address) not in found:
|
||||
found.append(str(address))
|
||||
return found
|
||||
|
||||
|
||||
def metrics_ready(ctx):
|
||||
@@ -1275,8 +1270,8 @@ def metrics_ready(ctx):
|
||||
|
||||
|
||||
def webdav_ready(ctx):
|
||||
"""WebDAV of the sites' folders is served by Caddy, on the server's own name, while it is on and HTTPS is ready."""
|
||||
return bool(ctx['webdav_enabled'] and https_ready(ctx))
|
||||
"""WebDAV of the sites' folders is served by Caddy, on the server's HTTPS names, while it is on."""
|
||||
return bool(ctx['webdav_enabled'])
|
||||
|
||||
|
||||
def packages_installed(packages):
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -20,8 +20,8 @@ The root comes from one of ROOT_SOURCES, pki.root, fixed once the root exists:
|
||||
issuing CAs, the upstream CA, kept on cn=root; the upstream CA's certificate and CRL are the entry cn=upstream, and
|
||||
it stands between the root and the issuing CAs in every chain.
|
||||
|
||||
The certificates carry the URLs of pki.publish for their issuer's certificate (AIA) and CRL (CRL distribution point);
|
||||
PUBLISH_DIR holds the DER copies served there. distribute writes the files strongSwan, OpenVPN and the system's trust
|
||||
The certificates carry the URLs of linuxmanager.pki_base_urls for their issuer's certificate (AIA) and CRL (CRL
|
||||
distribution point); PUBLISH_DIR holds the DER copies Caddy serves there. distribute writes the files strongSwan, OpenVPN and the system's trust
|
||||
store read.
|
||||
|
||||
Callers hold locked() around every operation that writes, which is the lock of the user module's sessions too. A request
|
||||
@@ -592,11 +592,14 @@ def is_address(value):
|
||||
|
||||
def router_identities(name, ctx):
|
||||
"""The common name and the subject alternative names of one of the server's certificates (ROUTER_CERTS): the VPN
|
||||
server and the HTTPS certificates name wan.local_fqdn, and the site-to-site certificate also the local identity of each
|
||||
site_to_site connection with certificate authentication, the public or the internal address of its
|
||||
local_id_mode; None while such an identity is not known yet."""
|
||||
server certificate names wan.local_fqdn, the HTTPS certificate its HTTPS names and addresses (https_sans), and the
|
||||
site-to-site certificate wan.local_fqdn and the local identity of each site_to_site connection with certificate
|
||||
authentication, the public or the internal address of its local_id_mode; None while such an identity is not known
|
||||
yet."""
|
||||
fqdn = ctx['local_fqdn']
|
||||
if name in ('vpn-server', 'https'):
|
||||
if name == 'https':
|
||||
return https_sans(ctx)[0], https_sans(ctx)
|
||||
if name == 'vpn-server':
|
||||
return fqdn, [fqdn]
|
||||
names = [fqdn]
|
||||
for connection in ctx['connections']:
|
||||
@@ -620,7 +623,7 @@ def ensure_router_cert(connection, cfg, ctx, name, urls):
|
||||
return
|
||||
subject, sans = identities
|
||||
current = holders(connection, ca, router_condition(name))
|
||||
wanted = {f'IP:{value}' if is_address(value) else f'DNS:{value.lower()}' for value in sans}
|
||||
wanted = san_set(sans)
|
||||
if current:
|
||||
_, cert, _ = current[0]
|
||||
if not renewal_due(cert) and issued_by(cert, issuer['cert']) and common_name(cert) == subject and \
|
||||
@@ -916,10 +919,21 @@ def chain_pem(chain):
|
||||
return b''.join(cert_pem(cert) for cert in chain)
|
||||
|
||||
|
||||
def https_sans(ctx):
|
||||
"""The subject alternative names of the server's HTTPS certificate, the first its common name: its HTTPS names
|
||||
(linuxmanager.https_names) and, while https.ip_sans is on, its addresses (linuxmanager.https_addresses)."""
|
||||
return [*ctx['https_names'], *ctx['https_ips']]
|
||||
|
||||
|
||||
def san_set(values):
|
||||
"""The SAN values of a certificate (san_values) that names the DNS names and IP addresses of values name."""
|
||||
return {f'IP:{value}' if is_address(value) else f'DNS:{value.lower()}' for value in values}
|
||||
|
||||
|
||||
def served_certificate(connection, cfg):
|
||||
"""What Caddy serves for wan.local_fqdn: (served, chain, key), served being https.certificate, or self-signed while
|
||||
"""What Caddy serves for the HTTPS names: (served, chain, key), served being https.certificate, or self-signed while
|
||||
the chosen certificate is not available; (acme, [], None) with acme, and (None, [], None) while there is none."""
|
||||
source, fqdn = cfg['https']['certificate'], cfg['wan']['local_fqdn'].strip().lower()
|
||||
source, fqdn = cfg['https']['certificate'], linuxmanager.https_names(cfg)[0]
|
||||
if source == 'acme':
|
||||
return 'acme', [], None
|
||||
if source == 'ca':
|
||||
@@ -935,22 +949,25 @@ def served_certificate(connection, cfg):
|
||||
return None, [], None
|
||||
|
||||
|
||||
def ensure_host_cert(connection, cfg):
|
||||
"""Make the self-signed certificate of wan.local_fqdn while https.certificate is self-signed, or while the chosen
|
||||
certificate is not available, when there is none, it is due for renewal or it names another name; the notices."""
|
||||
source, fqdn = cfg['https']['certificate'], cfg['wan']['local_fqdn'].strip().lower()
|
||||
if source == 'acme' or not cfg['https']['enabled'] or not fqdn:
|
||||
def ensure_host_cert(connection, cfg, ctx):
|
||||
"""Make the self-signed certificate of the HTTPS names and addresses (https_sans) while https.certificate is
|
||||
self-signed, or while the chosen certificate is not available, when there is none, it is due for renewal or it names
|
||||
other names; the notices."""
|
||||
source, sans = cfg['https']['certificate'], https_sans(ctx)
|
||||
fqdn = sans[0]
|
||||
if source == 'acme':
|
||||
return []
|
||||
served, _, _ = served_certificate(connection, cfg)
|
||||
if served == source and served != 'self-signed':
|
||||
return []
|
||||
entry = host_entry(connection)
|
||||
current = entry['chain'][0] if entry and entry['kind'] == 'self-signed' and entry['chain'] else None
|
||||
if current is None or renewal_due(current) or not usable(current, fqdn) or common_name(current) != fqdn:
|
||||
if current is None or renewal_due(current) or not usable(current, fqdn) or common_name(current) != fqdn or \
|
||||
set(san_values(current)) != san_set(sans):
|
||||
template = linuxmanager.pki_templates(cfg)['mtls']
|
||||
key = new_key(template['key'])
|
||||
cert = sign(fqdn, key.public_key(), None, key, cfg['https']['self_signed_days'],
|
||||
leaf_extensions(cfg, template, general_names([fqdn], {'dns'})))
|
||||
leaf_extensions(cfg, template, general_names(sans, {'dns', 'ip'})))
|
||||
update_host(connection, {'linuxManagerCertificateChain': cert_pem(cert), 'linuxManagerPrivateKey': key_pem(key),
|
||||
'linuxManagerKind': b'self-signed'})
|
||||
if source == 'self-signed':
|
||||
@@ -961,7 +978,7 @@ def ensure_host_cert(connection, cfg):
|
||||
|
||||
|
||||
def https_files(cfg):
|
||||
"""The PEM chain and key Caddy serves for wan.local_fqdn, None with https.certificate acme or while there is none."""
|
||||
"""The PEM chain and key Caddy serves for the HTTPS names, None with https.certificate acme or while there is none."""
|
||||
with directory() as connection:
|
||||
served, chain, key = served_certificate(connection, cfg)
|
||||
if served in (None, 'acme'):
|
||||
@@ -988,14 +1005,13 @@ def https_status(cfg):
|
||||
|
||||
|
||||
def https_csr(cfg):
|
||||
"""Make a key and a CSR for wan.local_fqdn, to be signed by another CA, replacing a pending one: {csr} in PEM."""
|
||||
fqdn = cfg['wan']['local_fqdn'].strip().lower()
|
||||
if not fqdn:
|
||||
raise Failure('the server has no wan.local_fqdn', 4)
|
||||
"""Make a key and a CSR for the HTTPS names (linuxmanager.https_names), to be signed by another CA, replacing a
|
||||
pending one: {csr} in PEM."""
|
||||
names = linuxmanager.https_names(cfg)
|
||||
key = new_key(linuxmanager.pki_templates(cfg)['mtls']['key'])
|
||||
request = (x509.CertificateSigningRequestBuilder()
|
||||
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, fqdn)]))
|
||||
.add_extension(x509.SubjectAlternativeName([x509.DNSName(fqdn)]), False)
|
||||
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, names[0])]))
|
||||
.add_extension(x509.SubjectAlternativeName(general_names(names, {'dns', 'ip'})), False)
|
||||
.sign(key, digest(key)))
|
||||
pem = request.public_bytes(serialization.Encoding.PEM)
|
||||
with directory() as connection:
|
||||
@@ -1005,8 +1021,8 @@ def https_csr(cfg):
|
||||
|
||||
def keep_external(connection, cfg, chain, key):
|
||||
"""Keep an imported certificate of another CA as the server's HTTPS certificate: it must be the key's, valid now
|
||||
and name wan.local_fqdn; {subject, issuer, expires}."""
|
||||
fqdn = cfg['wan']['local_fqdn'].strip().lower()
|
||||
and name the first HTTPS name (linuxmanager.https_names); {subject, issuer, expires}."""
|
||||
fqdn = linuxmanager.https_names(cfg)[0]
|
||||
if cfg['https']['certificate'] != 'external':
|
||||
raise Failure('https.certificate is not external', 4)
|
||||
cert = chain[0]
|
||||
@@ -1160,11 +1176,11 @@ def provision(cfg, ctx):
|
||||
if not cfg['https']['certificate']:
|
||||
servers = authority(connection, 'servers')
|
||||
linuxmanager.choose_https_certificate(cfg, ctx, 'ca' if servers and servers['cert'] is not None else 'self-signed')
|
||||
https_ca = cfg['https']['enabled'] and cfg['https']['certificate'] == 'ca'
|
||||
https_ca = cfg['https']['certificate'] == 'ca'
|
||||
for name in ROUTER_CERTS:
|
||||
if component_on(ROUTER_CERTS[name][0]) and (name != 'https' or https_ca):
|
||||
ensure_router_cert(connection, cfg, ctx, name, urls)
|
||||
notices.extend(ensure_host_cert(connection, cfg))
|
||||
notices.extend(ensure_host_cert(connection, cfg, ctx))
|
||||
publish(connection)
|
||||
p2s = authority(connection, 'p2s')
|
||||
missing = connection.search_s(linuxmanager_ldap.USERS, ldap.SCOPE_ONELEVEL,
|
||||
@@ -1589,7 +1605,7 @@ def maintain(cfg):
|
||||
|
||||
def acme_url(cfg, name):
|
||||
"""The ACME directory of an issuing CA served by Caddy's ACME server."""
|
||||
return f'https://{cfg["wan"]["local_fqdn"].strip()}:{cfg["https"]["web_port"]}/acme/{name}/directory'
|
||||
return f'https://{linuxmanager.https_names(cfg)[0]}:{cfg["https"]["web_port"]}/acme/{name}/directory'
|
||||
|
||||
|
||||
def status(cfg):
|
||||
@@ -1691,7 +1707,7 @@ def status(cfg):
|
||||
if utc(cert, 'not_valid_after') <= soon:
|
||||
warnings.append(f'the server certificate {common_name(cert)} expires on {iso(utc(cert, "not_valid_after"))}')
|
||||
https_source = cfg['https']['certificate']
|
||||
if cfg['https']['enabled'] and https_source != 'acme':
|
||||
if https_source != 'acme':
|
||||
if served != https_source:
|
||||
warnings.append(f'the HTTPS certificate is {"self-signed" if served else "missing"} until the https.certificate '
|
||||
f'{https_source} certificate is available')
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -30,9 +30,6 @@ Pages:
|
||||
/ca the PKI: its settings, the root and issuing CAs, the certificates issued; change the
|
||||
settings, issue and revoke certificates, and take the certificate of an issuing CA
|
||||
and a root CRL signed offline (see ca())
|
||||
/pki/<name>.crt, /pki/<name>.crl
|
||||
the DER certificate and CRL of the root (root) and of each issuing CA, which the
|
||||
certificates name in their AIA and CRL distribution points; no authentication
|
||||
/shell while web.shell is true, a login shell of the user's console account on a terminal, for
|
||||
a member of admins whose console login is on and who has a TOTP token: POST signs the user in again,
|
||||
with the password and the TOTP code or with a passkey whose proof POST /shell/passkey begins,
|
||||
|
||||
@@ -8,11 +8,9 @@ from http.server import BaseHTTPRequestHandler
|
||||
|
||||
import ldap
|
||||
|
||||
import linuxmanager
|
||||
import linuxmanager_auth
|
||||
import linuxmanager_net
|
||||
import linuxmanager_oidc
|
||||
import linuxmanager_pki
|
||||
import linuxmanager_sites
|
||||
|
||||
from .auth import auth, auth_wait, refusal
|
||||
@@ -25,7 +23,7 @@ from .identities import account, groups, service_accounts, users
|
||||
from .logs import logs
|
||||
from .https import PATHS as HTTPS_PATHS, https
|
||||
from .metrics import metrics_history, metrics_settings
|
||||
from .pki import PUBLISHED, ca
|
||||
from .pki import ca
|
||||
from .shell import EDITOR_BODY_LIMIT, shell, shell_editor, shell_passkey, shell_ticket
|
||||
from .sites import SITE_FILES, site_files, sites
|
||||
from .status import cached, details, html_of, postgresql_databases, shown, text_of
|
||||
@@ -182,9 +180,6 @@ class Handler(BaseHTTPRequestHandler):
|
||||
extra += headers
|
||||
elif self.command not in ('GET', 'HEAD'):
|
||||
body, kind, code = b'Method not allowed\n', 'text/plain; charset=utf-8', 405
|
||||
elif path.startswith('/pki/') and linuxmanager.PKI_NAME.match(path[5:-4]) and path[-4:] in PUBLISHED and \
|
||||
(linuxmanager_pki.PUBLISH_DIR / path[5:]).is_file():
|
||||
body, kind, code = (linuxmanager_pki.PUBLISH_DIR / path[5:]).read_bytes(), PUBLISHED[path[-4:]], 200
|
||||
elif path in ('/status', '/'):
|
||||
document = shown(cached(), section(read_json(CONFIG_FILE), 'web').get('status_content'), self.client())
|
||||
agent = self.headers.get('User-Agent', '').lower()
|
||||
|
||||
@@ -11,7 +11,7 @@ import linuxmanager_pki
|
||||
from .common import PKI_STATUS, section_change
|
||||
|
||||
#: The settings of the https section PUT /https/settings changes.
|
||||
CHANGEABLE = ('acme_staging', 'certificate', 'self_signed_days', 'acme_provider', 'acme_url', 'acme_eab_key_id',
|
||||
CHANGEABLE = ('acme_staging', 'certificate', 'self_signed_days', 'ip_sans', 'acme_provider', 'acme_url', 'acme_eab_key_id',
|
||||
'acme_eab_mac_key', 'zerossl_api_key')
|
||||
|
||||
#: The secrets of the https section, which the answers give as <name>_set instead.
|
||||
@@ -34,7 +34,7 @@ def https(method, path, body):
|
||||
server's HTTPS certificate (linuxmanager_pki.https_status)
|
||||
PUT /https/settings change any of CHANGEABLE; the other settings of the section are changed on the server
|
||||
with linux-manager-config-edit, and a body naming one is 400
|
||||
POST /https/csr make a key and a CSR for wan.local_fqdn: {"csr"}
|
||||
POST /https/csr make a key and a CSR for the HTTPS names: {"csr"}
|
||||
PUT /https/certificate take the certificate another CA signed for the CSR, PEM with its chain: {"certificate"}
|
||||
PUT /https/pfx take a PKCS#12 file of another CA's certificate: {"pfx" in base64, "password"}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The PKI: /ca, and the certificates and CRLs /pki/ serves without authentication."""
|
||||
"""The PKI: /ca."""
|
||||
|
||||
import ldap
|
||||
|
||||
@@ -7,9 +7,6 @@ import linuxmanager_pki
|
||||
|
||||
from .common import PKI_STATUS
|
||||
|
||||
#: A file /pki/ serves: the certificate or the CRL of a CA, and its content type.
|
||||
PUBLISHED = {'.crt': 'application/pkix-cert', '.crl': 'application/pkix-crl'}
|
||||
|
||||
|
||||
def ca(method, path, body):
|
||||
"""Answer a /ca request with linuxmanager_pki: the HTTP status and the JSON document.
|
||||
|
||||
@@ -80,9 +80,15 @@ CADDY_PKI_DIR = pathlib.Path('/etc/caddy/linux-manager-pki')
|
||||
#: The certificates and keys of the sites of tls file, <site>/cert.pem and key.pem.
|
||||
CADDY_SITES_DIR = pathlib.Path('/etc/caddy/linux-manager-sites')
|
||||
|
||||
#: The certificate and key of wan.local_fqdn Caddy serves when they come from no ACME CA.
|
||||
#: The certificate and key of the HTTPS names Caddy serves when they come from no ACME CA.
|
||||
CADDY_HTTPS_DIR = pathlib.Path('/etc/caddy/linux-manager-https')
|
||||
|
||||
#: The units of Avahi, which announces <host name>.local with mDNS while wan.local_fqdn is not set.
|
||||
AVAHI_UNITS = ('avahi-daemon.socket', 'avahi-daemon.service')
|
||||
|
||||
#: The UDP port of mDNS.
|
||||
MDNS_PORT = 5353
|
||||
|
||||
#: The unit of dnsmasq, the resolver of the remote access clients.
|
||||
RESOLVER_UNIT = 'linux-manager-resolver.service'
|
||||
|
||||
@@ -122,6 +128,7 @@ BLOCKS = (
|
||||
('# BOOTSTRAP RULES START', '# BOOTSTRAP RULES END'),
|
||||
('# MANAGER RULES START', '# MANAGER RULES END'),
|
||||
('# HTTPS RULES START', '# HTTPS RULES END'),
|
||||
('# MDNS RULES START', '# MDNS RULES END'),
|
||||
('# METRICS RULES START', '# METRICS RULES END'),
|
||||
('# SITES RULES START', '# SITES RULES END'),
|
||||
('# DNS RULES START', '# DNS RULES END'),
|
||||
@@ -200,19 +207,6 @@ def strip_blocks(text):
|
||||
return ''.join(out)
|
||||
|
||||
|
||||
def is_configured(ctx):
|
||||
"""True once any feature is actually configured: routing, a VPN system, or a listener of the core.
|
||||
|
||||
While nothing is configured the package leaves the firewall alone: an
|
||||
install that has not been filled in yet must not start blocking traffic on
|
||||
a host that was working before.
|
||||
"""
|
||||
return any((linuxmanager.s2s_ready(ctx), linuxmanager.routing_ready(ctx),
|
||||
linuxmanager.p2s_ready(ctx), linuxmanager.wg_ready(ctx),
|
||||
linuxmanager.openvpn_ready(ctx), ctx['web_enabled'], linuxmanager.https_ready(ctx),
|
||||
linuxmanager.metrics_ready(ctx), linuxmanager.dns_ready(ctx), bool(ctx['sites'])))
|
||||
|
||||
|
||||
def filter_block(ctx):
|
||||
lines = []
|
||||
|
||||
@@ -277,6 +271,11 @@ def filter_block(ctx):
|
||||
if ctx['web_enabled']:
|
||||
lines += ['', '# WEB RULES START', *opened(ctx['web_listen'], ctx['web_port']), '# WEB RULES END']
|
||||
|
||||
# Without wan.local_fqdn, Avahi answers mDNS queries for <host name>.local on the internal side.
|
||||
if ctx['mdns'] and internal:
|
||||
lines += ['', '# MDNS RULES START', f'-A ufw-before-input -i {internal} -p udp --dport {MDNS_PORT} -j ACCEPT',
|
||||
'# MDNS RULES END']
|
||||
|
||||
if not SETUP_DONE.exists() and ctx['int_iface']:
|
||||
lines += [
|
||||
'',
|
||||
@@ -293,22 +292,18 @@ def filter_block(ctx):
|
||||
lines += ['', '# METRICS RULES START', *opened(ctx['metrics_listen'], ctx['metrics_port']),
|
||||
'# METRICS RULES END']
|
||||
|
||||
# The ACME CA reaches the HTTP challenge on the external interface while it issues the server's certificate, and
|
||||
# the CA files published on port 80 are read on both; the HTTPS ports are open on both.
|
||||
if linuxmanager.https_ready(ctx) and interfaces:
|
||||
publish = ctx['pki_publish']
|
||||
ports = [port for wanted, port in ((ctx['web_enabled'] or 'https' in publish or ctx['pki_acme'],
|
||||
ctx['https_web_port']),
|
||||
# The ACME CA reaches the HTTP challenge on the external interface while it issues the server's certificate; the
|
||||
# HTTPS ports are open on both.
|
||||
if interfaces:
|
||||
ports = [port for wanted, port in ((ctx['web_enabled'] or ctx['pki_acme'], ctx['https_web_port']),
|
||||
(True, ctx['https_manager_port']),
|
||||
(linuxmanager.metrics_ready(ctx), ctx['metrics_https_port']),
|
||||
(linuxmanager.webdav_ready(ctx), ctx['webdav_port']),
|
||||
('http-80' in publish, linuxmanager.ACME_HTTP_PORT),
|
||||
('https-default' in publish, linuxmanager.HTTPS_DEFAULT_PORT)) if wanted]
|
||||
(linuxmanager.webdav_ready(ctx), ctx['webdav_port'])) if wanted]
|
||||
lines += [
|
||||
'',
|
||||
'# HTTPS RULES START',
|
||||
*([f'-A ufw-before-input -i {ctx["wan_iface"]} -p tcp --dport {linuxmanager.ACME_HTTP_PORT} -j ACCEPT']
|
||||
if ctx['wan_iface'] and 'http-80' not in publish and ctx['https_certificate'] == 'acme' else []),
|
||||
if ctx['wan_iface'] and ctx['https_certificate'] == 'acme' else []),
|
||||
*(f'-A ufw-before-input -i {name} -p tcp --dport {port} -j ACCEPT' for name in interfaces for port in ports),
|
||||
'# HTTPS RULES END',
|
||||
]
|
||||
@@ -435,17 +430,6 @@ def setup_ufw(ctx):
|
||||
if not BEFORE_RULES.is_file():
|
||||
fail(f'{BEFORE_RULES} does not exist')
|
||||
|
||||
# Nothing configured: remove anything left from an earlier configuration
|
||||
# and touch nothing else.
|
||||
if not is_configured(ctx):
|
||||
original = BEFORE_RULES.read_text(encoding='utf-8')
|
||||
text = strip_blocks(original)
|
||||
if text == original:
|
||||
return False
|
||||
BEFORE_RULES.write_text(text, encoding='utf-8')
|
||||
remove_stale_nat(original, text)
|
||||
return True
|
||||
|
||||
if UFW_DEFAULTS.is_file():
|
||||
text = UFW_DEFAULTS.read_text(encoding='utf-8')
|
||||
updated = ''.join(
|
||||
@@ -732,6 +716,16 @@ def caddy_address(host, port, tls):
|
||||
return f'{"http://" if tls == "none" else ""}{host}:{port}'
|
||||
|
||||
|
||||
def manage_mdns(ctx):
|
||||
"""Run Avahi, which announces <host name>.local, one of the HTTPS names, with mDNS, while wan.local_fqdn is not set,
|
||||
and stop it while it is."""
|
||||
active = unit_is_active(AVAHI_UNITS[1])
|
||||
if ctx['mdns'] and not active:
|
||||
run(['systemctl', 'enable', '--now', *AVAHI_UNITS], check=False)
|
||||
elif not ctx['mdns'] and active:
|
||||
run(['systemctl', 'disable', '--now', *AVAHI_UNITS], check=False)
|
||||
|
||||
|
||||
def manage_resolver(changed):
|
||||
"""Run dnsmasq, the resolver of the remote access clients, while configure wrote its configuration, restarting it when
|
||||
that changed, and stop it when not. It starts after systemd-resolved has left the addresses it takes."""
|
||||
@@ -749,16 +743,20 @@ def manage_caddy(cfg, ctx):
|
||||
"""Run Caddy, a dependency of the package, which serves every HTTP and HTTPS port of the server's services and the
|
||||
web sites; the services listen on loopback only.
|
||||
|
||||
CADDYFILE serves over plain HTTP the web service on web.port while it is enabled, the manager on its port, or a
|
||||
redirect (308) to its HTTPS address while HTTPS is ready and https.disable_auto_redirect is off, and while metrics
|
||||
are enabled the metrics service on metrics.port. While HTTPS is ready, it serves the web service on
|
||||
https.web_port, the manager on https.manager_port, while metrics are enabled the metrics service on
|
||||
metrics.https_port, and while WebDAV is ready WebDAV on sites.webdav_port, all for wan.local_fqdn. Every site calls
|
||||
CADDYFILE serves over plain HTTP the web service on web.port while it is enabled and the manager on its port, and
|
||||
while metrics are enabled the metrics service on metrics.port. While https.disable_auto_redirect is off, a request
|
||||
of the web service for an HTTPS host is redirected (308) to https.web_port, and every request of the manager to
|
||||
https.manager_port, on the host it named when that is an HTTPS host, else on the first HTTPS name. It serves the
|
||||
web service on https.web_port, the manager on https.manager_port, while metrics are enabled the metrics service on
|
||||
metrics.https_port, and while WebDAV is ready WebDAV on sites.webdav_port, all for the HTTPS hosts: the HTTPS names
|
||||
(linuxmanager.https_names) and, with https.ip_sans and a certificate of its own, the addresses its certificate
|
||||
names; a client without SNI gets the certificate of the first HTTPS name. Every site calls
|
||||
its service on its loopback port. The certificate comes from the ACME CA of https.acme_provider, the global issuer,
|
||||
with https.certificate acme, and otherwise is the one linuxmanager_pki.https_files gives, written to
|
||||
CADDY_HTTPS_DIR; while that cannot be read, the HTTPS sites are left out, so that no ACME CA is asked for it. It
|
||||
also serves the CA files of linuxmanager_pki.PUBLISH_DIR at /pki/ on the endpoints of pki.publish that are Caddy's,
|
||||
and an ACME server at /acme/<name>/ on https.web_port for each issuing CA with acme and a certificate.
|
||||
also serves the CA files of linuxmanager_pki.PUBLISH_DIR at /pki/ on web.port, the Manager's port, https.web_port
|
||||
and https.manager_port, ahead of the redirect to HTTPS, and an ACME server at /acme/<name>/ on https.web_port for
|
||||
each issuing CA with acme and a certificate.
|
||||
|
||||
It serves each site of ctx's sites from its folder, with the TLS of the site: an issuing CA of tls ca issues its
|
||||
certificates, and the certificate and key of tls file are written to CADDY_SITES_DIR/<name>. The certificates and
|
||||
@@ -777,7 +775,7 @@ def manage_caddy(cfg, ctx):
|
||||
group = grp.getgrnam(CADDY_GROUP).gr_gid
|
||||
except KeyError:
|
||||
fail(f'the group {CADDY_GROUP} does not exist; is the caddy package installed?')
|
||||
https = linuxmanager.https_ready(ctx)
|
||||
https = True
|
||||
own = None
|
||||
if https and cfg['https']['certificate'] != 'acme':
|
||||
try:
|
||||
@@ -835,8 +833,12 @@ def manage_caddy(cfg, ctx):
|
||||
os.chown(folder / file, 0, group)
|
||||
linuxmanager_sites.ensure_folders(site['name'] for site in sites)
|
||||
names = linuxmanager.issuing_cas(cfg)
|
||||
hosts = [*ctx['https_names'], *(ctx['https_ips'] if own is not None else [])]
|
||||
caddy_ctx = dict(ctx, https=https, manager_port=linuxmanager.manager_port(),
|
||||
redirect=https and not cfg['https']['disable_auto_redirect'],
|
||||
https_name=ctx['https_names'][0],
|
||||
https_hosts=[f'[{host}]' if ':' in host else host for host in hosts],
|
||||
redirect_hosts=[host for host in hosts if ':' not in host],
|
||||
web_loopback_port=linuxmanager.WEB_LOOPBACK_PORT,
|
||||
manager_loopback_port=linuxmanager.MANAGER_LOOPBACK_PORT,
|
||||
metrics_loopback_port=linuxmanager.METRICS_LOOPBACK_PORT,
|
||||
@@ -1046,6 +1048,8 @@ def refresh_web(cfg, ctx):
|
||||
'external_addresses': ctx['local_addr_list'],
|
||||
'internal_address': ctx['int_addr'],
|
||||
'internal_gateway': ctx['int_gateway_ip'],
|
||||
'https_names': ctx['https_names'],
|
||||
'https_addresses': ctx['https_ips'],
|
||||
'local_cidrs': ctx['local_cidr_list'],
|
||||
'client_dns': ctx['p2s_resolver_addrs'] if linuxmanager.RESOLVER_CONF.exists() else [],
|
||||
'site_to_site': [{
|
||||
@@ -1098,6 +1102,9 @@ def main():
|
||||
f'set general.platform in {linuxmanager.CONFIG_FILE}')
|
||||
progress('deferred', 'configuration', f'general.platform is none; set it in {linuxmanager.CONFIG_FILE}')
|
||||
return 0
|
||||
# Until a run has succeeded, a file that names no HTTPS certificate source leaves the choice to this run.
|
||||
if not SETUP_DONE.exists() and not linuxmanager.read_settings().get('https', {}).get('certificate'):
|
||||
cfg['https']['certificate'] = ''
|
||||
|
||||
# The directory holds the PKI, which the configuration needs; its problem ends setup only after every other step.
|
||||
failed_step = 'user directory'
|
||||
@@ -1136,16 +1143,13 @@ def main():
|
||||
|
||||
progress('running', 'firewall')
|
||||
rules_changed = setup_ufw(ctx)
|
||||
if is_configured(ctx):
|
||||
status = run(['ufw', 'status'], check=False)
|
||||
if not status.stdout.startswith('Status: active'):
|
||||
# Only ever enable the firewall after making sure SSH survives it.
|
||||
run(['ufw', 'allow', '22/tcp'], check=False)
|
||||
run(['ufw', '--force', 'enable'])
|
||||
elif rules_changed:
|
||||
run(['ufw', 'reload'])
|
||||
status = run(['ufw', 'status'], check=False)
|
||||
if not status.stdout.startswith('Status: active'):
|
||||
# Only ever enable the firewall after making sure SSH survives it.
|
||||
run(['ufw', 'allow', '22/tcp'], check=False)
|
||||
run(['ufw', '--force', 'enable'])
|
||||
elif rules_changed:
|
||||
run(['ufw', 'reload'], check=False)
|
||||
run(['ufw', 'reload'])
|
||||
|
||||
progress('running', 'strongSwan')
|
||||
manage_strongswan(ctx, changed)
|
||||
@@ -1168,6 +1172,8 @@ def main():
|
||||
manage_openvpn(ctx, changed)
|
||||
progress('running', 'HTTPS proxy')
|
||||
manage_caddy(cfg, ctx)
|
||||
progress('running', 'mDNS')
|
||||
manage_mdns(ctx)
|
||||
progress('running', 'WebDAV')
|
||||
manage_webdav(ctx)
|
||||
progress('running', 'name server')
|
||||
|
||||
@@ -106,7 +106,6 @@
|
||||
"key": "rsa-4096",
|
||||
"crl_days": 7,
|
||||
"root_crl_days": 180,
|
||||
"publish": ["http"],
|
||||
"p2s_name": "Linux Manager VPN CA",
|
||||
"s2s_name": "Linux Manager Site-to-Site CA",
|
||||
"issuing_cas": {
|
||||
|
||||
@@ -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 ) )
|
||||
@@ -1,6 +1,9 @@
|
||||
# Written by linux-manager-setup from /etc/linux-manager/linux-manager.json and the web sites; edits are overwritten.
|
||||
{
|
||||
auto_https disable_redirects
|
||||
{%- if https_tls %}
|
||||
default_sni {{ https_name }}
|
||||
{%- endif %}
|
||||
{%- if https_email %}
|
||||
email {{ https_email }}
|
||||
{%- endif %}
|
||||
@@ -33,23 +36,54 @@
|
||||
}
|
||||
{%- endif %}
|
||||
}
|
||||
{#- The CA certificates and CRLs of directory at /pki/, as DER with the content types of RFC 5280. #}
|
||||
{%- macro pki_files(directory) %}
|
||||
handle_path /pki/* {
|
||||
@crt path *.crt
|
||||
@crl path *.crl
|
||||
header @crt Content-Type application/pkix-cert
|
||||
header @crl Content-Type application/pkix-crl
|
||||
root * {{ directory }}
|
||||
file_server
|
||||
}
|
||||
{%- endmacro %}
|
||||
{#- The addresses of an HTTPS site on port: the HTTPS hosts. #}
|
||||
{%- macro https_site(port) %}{% for host in https_hosts %}{{ host }}:{{ port }}{{ ', ' if not loop.last else '' }}{% endfor %}{% endmacro %}
|
||||
{% if web_enabled %}
|
||||
http://:{{ web_port }} {
|
||||
header -Server
|
||||
reverse_proxy {{ loopback }}:{{ web_loopback_port }} {
|
||||
header_down -Server
|
||||
{{- pki_files(pki_publish_dir) }}
|
||||
{%- if redirect %}
|
||||
@https host {{ redirect_hosts | join(' ') }}
|
||||
handle @https {
|
||||
redir https://{host}:{{ https_web_port }}{uri} 308
|
||||
}
|
||||
{%- endif %}
|
||||
handle {
|
||||
reverse_proxy {{ loopback }}:{{ web_loopback_port }} {
|
||||
header_down -Server
|
||||
}
|
||||
}
|
||||
}
|
||||
{% endif %}
|
||||
http://:{{ manager_port }} {
|
||||
header -Server
|
||||
{{- pki_files(pki_publish_dir) }}
|
||||
{%- if redirect %}
|
||||
redir https://{{ local_fqdn }}:{{ https_manager_port }}{uri} 308
|
||||
{%- else %}
|
||||
reverse_proxy {{ loopback }}:{{ manager_loopback_port }} {
|
||||
header_down -Server
|
||||
@https host {{ redirect_hosts | join(' ') }}
|
||||
handle @https {
|
||||
redir https://{host}:{{ https_manager_port }}{uri} 308
|
||||
}
|
||||
{%- endif %}
|
||||
handle {
|
||||
{%- if redirect %}
|
||||
redir https://{{ https_name }}:{{ https_manager_port }}{uri} 308
|
||||
{%- else %}
|
||||
reverse_proxy {{ loopback }}:{{ manager_loopback_port }} {
|
||||
header_down -Server
|
||||
}
|
||||
{%- endif %}
|
||||
}
|
||||
}
|
||||
{% if metrics_enabled %}
|
||||
http://:{{ metrics_port }} {
|
||||
@@ -59,18 +93,13 @@ http://:{{ metrics_port }} {
|
||||
}
|
||||
}
|
||||
{% endif %}
|
||||
{%- if https and (web_enabled or 'https' in pki_publish or acme_cas) %}
|
||||
{{ local_fqdn }}:{{ https_web_port }} {
|
||||
{%- if https and (web_enabled or acme_cas) %}
|
||||
{{ https_site(https_web_port) }} {
|
||||
header -Server
|
||||
{%- if https_tls %}
|
||||
tls {{ https_tls.cert }} {{ https_tls.key }}
|
||||
{%- endif %}
|
||||
{%- if 'https' in pki_publish %}
|
||||
handle_path /pki/* {
|
||||
root * {{ pki_publish_dir }}
|
||||
file_server
|
||||
}
|
||||
{%- endif %}
|
||||
{{- pki_files(pki_publish_dir) }}
|
||||
{%- for ca in acme_cas %}
|
||||
handle /acme/{{ ca }}/* {
|
||||
acme_server {
|
||||
@@ -89,46 +118,22 @@ http://:{{ metrics_port }} {
|
||||
}
|
||||
}
|
||||
{% endif %}
|
||||
{%- if https and 'http-80' in pki_publish %}
|
||||
http://{{ local_fqdn }} {
|
||||
header -Server
|
||||
handle_path /pki/* {
|
||||
root * {{ pki_publish_dir }}
|
||||
file_server
|
||||
}
|
||||
handle {
|
||||
respond 404
|
||||
}
|
||||
}
|
||||
{% endif %}
|
||||
{%- if https and 'https-default' in pki_publish %}
|
||||
{{ local_fqdn }}:443 {
|
||||
header -Server
|
||||
{%- if https_tls %}
|
||||
tls {{ https_tls.cert }} {{ https_tls.key }}
|
||||
{%- endif %}
|
||||
handle_path /pki/* {
|
||||
root * {{ pki_publish_dir }}
|
||||
file_server
|
||||
}
|
||||
handle {
|
||||
respond 404
|
||||
}
|
||||
}
|
||||
{% endif %}
|
||||
{%- if https %}
|
||||
{{ local_fqdn }}:{{ https_manager_port }} {
|
||||
{{ https_site(https_manager_port) }} {
|
||||
header -Server
|
||||
{%- if https_tls %}
|
||||
tls {{ https_tls.cert }} {{ https_tls.key }}
|
||||
{%- endif %}
|
||||
reverse_proxy {{ loopback }}:{{ manager_loopback_port }} {
|
||||
header_down -Server
|
||||
{{- pki_files(pki_publish_dir) }}
|
||||
handle {
|
||||
reverse_proxy {{ loopback }}:{{ manager_loopback_port }} {
|
||||
header_down -Server
|
||||
}
|
||||
}
|
||||
}
|
||||
{% endif %}
|
||||
{%- if https and metrics_enabled %}
|
||||
{{ local_fqdn }}:{{ metrics_https_port }} {
|
||||
{{ https_site(metrics_https_port) }} {
|
||||
header -Server
|
||||
{%- if https_tls %}
|
||||
tls {{ https_tls.cert }} {{ https_tls.key }}
|
||||
@@ -139,7 +144,7 @@ http://{{ local_fqdn }} {
|
||||
}
|
||||
{% endif %}
|
||||
{%- if webdav %}
|
||||
{{ local_fqdn }}:{{ webdav_port }} {
|
||||
{{ https_site(webdav_port) }} {
|
||||
header -Server
|
||||
{%- if https_tls %}
|
||||
tls {{ https_tls.cert }} {{ https_tls.key }}
|
||||
|
||||
@@ -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())
|
||||
@@ -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
|
||||
+12
-8
@@ -11,13 +11,13 @@ Issue and Settings are on every tab but Server.
|
||||
- **Issue:** a certificate from a CSR, saved with its chain, or with a key the server makes, saved
|
||||
as a PFX file protected by a password; the server keeps no copy of the key.
|
||||
- **Settings:** the names of the P2S and S2S CAs while they do not exist yet, the lifetimes, key
|
||||
type, CRL validity, publishing endpoints and, with a Simple CA root, the URL of the service.
|
||||
type, CRL validity and, with a Simple CA root, the URL of the service.
|
||||
- **Warnings:** what needs attention, such as a CRL about to expire.
|
||||
|
||||
## Tabs
|
||||
|
||||
- **Server:** the first tab, shown also while the PKI cannot be read: HTTPS and the name it is
|
||||
for, with a chip while the server's certificate has a source other than ACME, and a settings
|
||||
- **Server:** the first tab, shown also while the PKI cannot be read: HTTPS and the names and
|
||||
addresses it is for, with a chip while the server's certificate has a source other than ACME, and a settings
|
||||
button; the server's certificate, when it is not ACME's, with its issuer and expiry; the ACME
|
||||
CA, with a chip while it is Let's Encrypt's staging environment, and a settings button (see
|
||||
Server HTTPS below); and Caddy, which serves every HTTP and HTTPS port of the server, with its
|
||||
@@ -47,15 +47,19 @@ Issue and Settings are on every tab but Server.
|
||||
## Server HTTPS
|
||||
|
||||
The settings button of the HTTPS row sets the **certificate of the server**: ACME; self-signed,
|
||||
with its validity in days; the Servers Issuing CA of the server's PKI; or another CA. Until the
|
||||
chosen certificate is available, the server serves a self-signed one and warns.
|
||||
with its validity in days; the Servers Issuing CA of the server's PKI; or another CA. Without
|
||||
ACME, a checkbox also names the server's IP addresses in the certificate, to reach it over HTTPS
|
||||
by address. Until the chosen certificate is available, the server serves a self-signed one and warns.
|
||||
|
||||
The source is self-signed unless the configuration names another; ACME is used only when it is
|
||||
chosen. The first setup of a new installation chooses the Servers Issuing CA when the root CA and
|
||||
that CA are available, as with a root the server creates, else self-signed.
|
||||
While HTTPS is on, the Manager's plain HTTP address redirects to its HTTPS address, unless the
|
||||
that CA are available, as with a root the server creates, else self-signed; it does so also when
|
||||
the configuration it is given names no source.
|
||||
HTTPS is always on, for `wan.local_fqdn` or, without it, the host name and `<host name>.local`;
|
||||
with `https.ip_sans` the certificate also names the server's addresses. A plain HTTP request for
|
||||
those names is redirected to HTTPS, on the status page's port and the Manager's, unless the
|
||||
installer's `https_disable_auto_redirect` or `https.disable_auto_redirect` says otherwise; the
|
||||
status page never redirects.
|
||||
status page stays on plain HTTP by address, and `/pki/` on plain HTTP always.
|
||||
|
||||
The settings button of the ACME CA row sets the ACME CA of the server's certificate with ACME, and
|
||||
of the web sites with TLS ACME: Let's Encrypt, with **Staging environment** for routers rebuilt
|
||||
|
||||
+2
-4
@@ -23,16 +23,14 @@ Back returns to the previous topic and the house icon to this one.
|
||||
| Certificates | [Certificates](certificates.md) |
|
||||
| Web Sites | [Sites](sites.md), [Files](site-files.md), [DNS](dns.md) |
|
||||
| Docker | [Docker](docker.md) |
|
||||
| Header | [Shell](shell.md), [Account](account.md) |
|
||||
| Shell | [Shell](shell.md) |
|
||||
| Header | [Account](account.md) |
|
||||
|
||||
## Header
|
||||
|
||||
- **Page menu** (right end): switches between the pages; its button names the page shown.
|
||||
- **Help** (question mark, left of the page menu): opens and closes this panel; the page moves left
|
||||
while it is open.
|
||||
- **Shell** (terminal icon, administrators): a shell on the server; pressed on the Shell page, it
|
||||
returns to the page it was opened from. With **Open the shell in a new tab** in the settings,
|
||||
it opens the shell in a tab of its own.
|
||||
- **Your name**: opens your account; pressed there, it returns to the page it was opened from.
|
||||
- **Sign out**, **Settings** (gear, but not on the account page) and **Theme** (light, dark or the system's).
|
||||
|
||||
|
||||
@@ -39,7 +39,8 @@ their password and, when enrolled, the code.
|
||||
- The eye opens the device's configuration; the download gives `<user>-<n>.conf`, with a
|
||||
placeholder for the device's private key, which the server never has.
|
||||
- The remove button removes a peer after a confirmation.
|
||||
- **Server:** the server's public key with a copy icon, the endpoint and the allowed IPs a device
|
||||
needs; **Show config** opens a device configuration with placeholders.
|
||||
- **Server:** the server's public key with a copy icon on a page opened over HTTPS, the endpoint
|
||||
and the allowed IPs a device needs; **Show config** opens a device configuration with
|
||||
placeholders, with a Copy button over HTTPS.
|
||||
- In the configuration dialogs a switch leaves out the `[Interface]` and `PrivateKey` lines, which
|
||||
WireGuard for Windows fills in for a new empty tunnel.
|
||||
+5
-3
@@ -11,9 +11,11 @@ The Overview tab shows the state of the server, read every 10 seconds by default
|
||||
IKEv2, OpenVPN and WireGuard; and the status web service and its port.
|
||||
- **Services:** the state of each of the server's systemd services and of Caddy; the chip on the
|
||||
title bar tells whether the server's services are active.
|
||||
- **Addresses:** links to the status page over HTTPS and over plain HTTP, and to the
|
||||
Manager over HTTPS, each opening in a new tab; and the issuer and the discovery URL of the
|
||||
server's OpenID Provider, each with a copy icon, or off while the provider is disabled (see
|
||||
- **Addresses:** links to the status page and the Manager over HTTPS for the server's names (and
|
||||
its addresses with `https.ip_sans`), and over plain HTTP: the status page by address, and both
|
||||
by name and the Manager by address too while the redirect to HTTPS is off; each opens in a new
|
||||
tab. Then the issuer and the discovery URL of the server's OpenID Provider, each with a copy
|
||||
icon over HTTPS, or off while the provider is disabled (see
|
||||
[Service accounts](service-accounts.md#openid-provider)).
|
||||
- **Backup:** the result of the last run, the next run and Run now (see [Backup](backup.md)).
|
||||
- **PostgreSQL:** each cluster with its main settings and its databases with their sizes.
|
||||
|
||||
@@ -23,9 +23,9 @@ Collector reading the server's metrics. They cannot sign in to the Manager.
|
||||
## OpenID Provider
|
||||
|
||||
The server can sign its users in to other systems with OpenID Connect. Its issuer and discovery
|
||||
URL are on the Addresses panel of the [Overview](router.md), each with a copy icon, and while it is
|
||||
enabled the title of the list has the number of its clients. It is turned on on the server as
|
||||
root:
|
||||
URL are on the Addresses panel of the [Overview](router.md), each with a copy icon on a page
|
||||
opened over HTTPS, and while it is enabled the title of the list has the number of its clients.
|
||||
It is turned on on the server as root:
|
||||
|
||||
```sh
|
||||
linux-manager-config-edit set --restart oidc.enabled true
|
||||
|
||||
+4
-4
@@ -9,8 +9,8 @@ a local account root chose.
|
||||
[Account](account.md)).
|
||||
- **Closing:** the server ends the shell after `web.shell_idle_minutes` without a keystroke; the
|
||||
page shows the reason and keeps the terminal readable. Leaving the page ends the shell too;
|
||||
with **Open the shell in a new tab** in the [settings](index.md#settings), the shell button opens
|
||||
it in a tab of its own, which other pages leave alone.
|
||||
with **Open the shell in a new tab** in the [settings](index.md#settings), the page menu opens
|
||||
the Shell page in a tab of its own, which other pages leave alone.
|
||||
|
||||
## Editor
|
||||
|
||||
@@ -23,8 +23,8 @@ lme /etc/hosts ~/notes.txt
|
||||
|
||||
- **Tabs:** each file has a tab with its name, and its path as the tooltip. A dot marks unsaved
|
||||
changes, and the cross closes the tab, asking first when there are unsaved changes.
|
||||
- **Editor icon** (left of the shell icon): shown while a file is open. It switches between the
|
||||
terminal and the editor; the shell keeps running.
|
||||
- **Editor icon** (left of your name in the header): shown while a file is open. It switches
|
||||
between the terminal and the editor; the shell keeps running.
|
||||
- **Minimap button** (left of Save): shows or hides the minimap at the right edge of the editor.
|
||||
This browser remembers the choice.
|
||||
- **Save** (or Ctrl+S): writes the file on the server, as your console account. When the file
|
||||
|
||||
+2
-2
@@ -8,8 +8,8 @@ and the name server of their domain on the [DNS](dns.md) page.
|
||||
|
||||
- **State:** whether the sites are served.
|
||||
- **Largest upload:** the largest file or zip archive the Files tab and the server's API take.
|
||||
- **WebDAV:** whether the folders are served over WebDAV, and its URL with a copy icon. WebDAV is
|
||||
switched on the [System](system.md) tab, which installs rclone.
|
||||
- **WebDAV:** whether the folders are served over WebDAV, and its URL with a copy icon over HTTPS.
|
||||
WebDAV is switched on the [System](system.md) tab, which installs rclone.
|
||||
|
||||
**Settings** edits the state, the largest upload and the WebDAV port.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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
+70
@@ -0,0 +1,70 @@
|
||||
#!/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 argparse
|
||||
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():
|
||||
argparse.ArgumentParser(description=__doc__.splitlines()[0]).parse_args()
|
||||
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
@@ -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
@@ -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
|
||||
|
||||
|
||||
|
||||
+52
-28
@@ -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.
|
||||
|
||||
@@ -62,7 +62,8 @@ The configurations in `configs/` have placeholders that are filled in for each s
|
||||
|
||||
- `@PSK@`: the pre-shared key, filled in on the Mac; the file reaches the server through the Vault;
|
||||
- `@ETH0@` and `@ETH1@`: the names of its interfaces;
|
||||
- `@CIDR0@`: the network of its first address.
|
||||
- `@CIDR0@`: the network of its first address;
|
||||
- `@FQDN@`: in `dev.json`, the name of the dev VM, `--fqdn` of `lm-dev-vm.py`.
|
||||
|
||||
## Secrets
|
||||
|
||||
@@ -91,35 +92,54 @@ 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",
|
||||
"LXD_DEV_FQDN": "lm-dev.example.org"
|
||||
}
|
||||
```
|
||||
|
||||
## 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/`,
|
||||
`dev.json` by default, which keeps the status page and the Manager on plain HTTP by name too
|
||||
(`https.disable_auto_redirect`); `@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
|
||||
else the package built last, in `out/` or `out/dev/`. The leased address is pinned on the VM's NIC, and these ports lead
|
||||
to the VM:
|
||||
|
||||
- `7080` to the Manager;
|
||||
- `7081` to the status web service;
|
||||
- `7080` and `7443` to the Manager, over HTTP and HTTPS;
|
||||
- `7081` and `7444` to the status web service, over HTTP and HTTPS;
|
||||
- `2222` to SSH, port `22`.
|
||||
|
||||
In a test project they lead through a network forward on the project's `wan`, whose listen address
|
||||
@@ -141,18 +161,20 @@ 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/` |
|
||||
| `--config` | | `dev.json` | The configuration from `configs/` |
|
||||
| `--listen` | `LXD_LISTEN` | the remote URL's host | Outside a test project, the address the proxies listen on |
|
||||
| `--forward-address` | `LXD_FORWARD_ADDRESS` | allocated | In a test project, the forward's listen address, one of the uplink's routes, so a recreated VM keeps it |
|
||||
| `--fqdn` | `LXD_DEV_FQDN` | `lm-dev.test` | The name of the VM, `@FQDN@` of `dev.json`: the Manager and the status web service answer HTTPS for it, so it has to resolve to the forward or proxy address |
|
||||
| `--no-otp` | | off | With `create`, enrol no TOTP token for `admin` |
|
||||
| `--deb` | | the package built last | Outside a test project, the package to install |
|
||||
|
||||
@@ -228,12 +250,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 +268,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 +288,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
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
{
|
||||
"general": {"platform": "generic", "mode": "manual"},
|
||||
"router": {"enabled": false},
|
||||
"vpn": {"enabled": false},
|
||||
"general": {"platform": "generic"},
|
||||
"interfaces": {"external": "@ETH0@"},
|
||||
"wan": {"local_fqdn": "lm-core.test"},
|
||||
"https": {"enabled": false}
|
||||
"wan": {"local_fqdn": "lm-core.test"}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"general": {"platform": "generic"},
|
||||
"interfaces": {"external": "@ETH0@"},
|
||||
"wan": {"local_fqdn": "@FQDN@"},
|
||||
"https": {"disable_auto_redirect": true}
|
||||
}
|
||||
@@ -1,11 +1,6 @@
|
||||
{
|
||||
"general": {"platform": "generic", "mode": "manual"},
|
||||
"router": {"enabled": false},
|
||||
"vpn": {"enabled": false},
|
||||
"general": {"platform": "generic"},
|
||||
"interfaces": {"external": "@ETH0@"},
|
||||
"wan": {"local_fqdn": "lm-nat.test"},
|
||||
"local": {"cidrs": ["@CIDR0@"]},
|
||||
"wireguard": {"enabled": false, "address": "10.66.0.1/24", "listen_port": 51820},
|
||||
"openvpn": {"enabled": false, "address_pool": "10.67.0.0/24", "port": 1194, "protocol": "udp"},
|
||||
"https": {"enabled": false}
|
||||
"local": {"cidrs": ["@CIDR0@"]}
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
{
|
||||
"general": {"platform": "generic", "mode": "manual"},
|
||||
"router": {"enabled": false},
|
||||
"general": {"platform": "generic"},
|
||||
"vpn": {"enabled": true},
|
||||
"interfaces": {"external": "@ETH0@"},
|
||||
"wan": {"local_fqdn": "lm-nat.test"},
|
||||
"local": {"cidrs": ["@CIDR0@"]},
|
||||
"wireguard": {"enabled": true, "address": "10.66.0.1/24", "listen_port": 51820},
|
||||
"openvpn": {"enabled": true, "address_pool": "10.67.0.0/24", "port": 1194, "protocol": "udp"},
|
||||
"https": {"enabled": false}
|
||||
"wireguard": {"enabled": true, "address": "10.66.0.1/24"},
|
||||
"openvpn": {"enabled": true, "address_pool": "10.67.0.0/24"}
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
{
|
||||
"general": {"platform": "generic", "mode": "manual"},
|
||||
"router": {"enabled": false},
|
||||
"vpn": {"enabled": false},
|
||||
"general": {"platform": "generic"},
|
||||
"interfaces": {"external": "@ETH0@"},
|
||||
"wan": {"local_fqdn": "lm-oidc.test"},
|
||||
"https": {"enabled": true, "certificate": "ca"},
|
||||
"oidc": {"enabled": true}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"general": {"platform": "generic", "mode": "manual"},
|
||||
"router": {"enabled": false},
|
||||
"vpn": {"enabled": true},
|
||||
"interfaces": {"external": "@ETH0@"},
|
||||
"wan": {"local_fqdn": "lm-offline.test"},
|
||||
"local": {"cidrs": ["@CIDR0@"]},
|
||||
"openvpn": {"enabled": true, "address_pool": "10.67.0.0/24", "port": 1194, "protocol": "udp"},
|
||||
"pki": {"root": "offline"},
|
||||
"https": {"enabled": false}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"general": {"platform": "generic", "mode": "manual"},
|
||||
"router": {"enabled": false},
|
||||
"vpn": {"enabled": true},
|
||||
"interfaces": {"external": "@ETH0@"},
|
||||
"wan": {"local_fqdn": "lm-simple-ca.test"},
|
||||
"local": {"cidrs": ["@CIDR0@"]},
|
||||
"openvpn": {"enabled": true, "address_pool": "10.67.0.0/24", "port": 1194, "protocol": "udp"},
|
||||
"pki": {"root": "simple-ca", "simple_ca_url": "https://10.188.96.4:8443"},
|
||||
"https": {"enabled": false}
|
||||
}
|
||||
@@ -1,14 +1,12 @@
|
||||
{
|
||||
"general": {"platform": "generic", "mode": "manual"},
|
||||
"router": {"enabled": false},
|
||||
"general": {"platform": "generic"},
|
||||
"vpn": {"enabled": true},
|
||||
"interfaces": {"external": "@ETH0@"},
|
||||
"wan": {"local_fqdn": "lm-s2s-a.test"},
|
||||
"local": {"cidrs": ["172.31.31.0/24"]},
|
||||
"site_to_site": {
|
||||
"to-b": {"addrs": ["172.31.20.20"], "id": "lm-s2s-b.test", "cidrs": ["172.31.32.0/24"],
|
||||
"local_cidrs": ["172.31.31.0/24"], "local_id_mode": "fqdn", "auth": "psk", "psk": "@PSK@"}
|
||||
"local_cidrs": ["172.31.31.0/24"], "psk": "@PSK@"}
|
||||
},
|
||||
"wireguard": {"enabled": true, "address": "10.66.0.1/24", "listen_port": 51820},
|
||||
"https": {"enabled": false}
|
||||
"wireguard": {"enabled": true, "address": "10.66.0.1/24"}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"general": {"platform": "generic", "mode": "manual"},
|
||||
"general": {"platform": "generic"},
|
||||
"router": {"enabled": true},
|
||||
"vpn": {"enabled": true},
|
||||
"interfaces": {"external": "@ETH0@", "internal": "@ETH1@"},
|
||||
@@ -7,8 +7,7 @@
|
||||
"local": {"cidrs": ["172.31.31.0/24"], "int_addr": "172.31.21.10", "int_gateway_ip": "172.31.21.20"},
|
||||
"site_to_site": {
|
||||
"to-b": {"addrs": ["172.31.20.20"], "id": "lm-s2s-b.test", "cidrs": ["172.31.32.0/24"],
|
||||
"local_cidrs": ["172.31.31.0/24"], "local_id_mode": "fqdn", "auth": "psk", "psk": "@PSK@"}
|
||||
"local_cidrs": ["172.31.31.0/24"], "psk": "@PSK@"}
|
||||
},
|
||||
"wireguard": {"enabled": true, "address": "10.66.0.1/24", "listen_port": 51820},
|
||||
"https": {"enabled": false}
|
||||
"wireguard": {"enabled": true, "address": "10.66.0.1/24"}
|
||||
}
|
||||
@@ -1,13 +1,11 @@
|
||||
{
|
||||
"general": {"platform": "generic", "mode": "manual"},
|
||||
"general": {"platform": "generic"},
|
||||
"router": {"enabled": true},
|
||||
"vpn": {"enabled": false},
|
||||
"interfaces": {"external": "@ETH0@", "internal": "@ETH1@"},
|
||||
"wan": {"local_fqdn": "lm-s2s-b.test"},
|
||||
"local": {"cidrs": ["172.31.32.0/24"], "int_addr": "172.31.22.10", "int_gateway_ip": "172.31.22.20"},
|
||||
"site_to_site": {
|
||||
"to-a": {"addrs": ["172.31.20.10"], "id": "lm-s2s-a.test", "cidrs": ["172.31.31.0/24"],
|
||||
"local_cidrs": ["172.31.32.0/24"], "local_id_mode": "fqdn", "auth": "psk", "psk": "@PSK@"}
|
||||
},
|
||||
"https": {"enabled": false}
|
||||
"local_cidrs": ["172.31.32.0/24"], "psk": "@PSK@"}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,8 @@ import { useEffect, useState, type FormEvent } from 'react'
|
||||
import OtpDialog from './OtpDialog.tsx'
|
||||
import PasskeyDialog from './PasskeyDialog.tsx'
|
||||
import ProfileDialog from './ProfileDialog.tsx'
|
||||
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { useBoard } from './useBoard.ts'
|
||||
import Toolbar from './Toolbar.tsx'
|
||||
import { ACCOUNT_SHAPE, CODE_PATTERN, USER_SHAPE, request, type Account, type User } from './api.ts'
|
||||
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, MenuItem, Stack, Switch, TextField, Typography } from '@mui/material'
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import { ACME_PROVIDERS, type AcmeProvider, type HttpsChange, type HttpsSettings } from './api.ts'
|
||||
|
||||
/** The labels of the ACME providers. */
|
||||
export const PROVIDER_LABELS: Record<AcmeProvider, string> = {
|
||||
letsencrypt: 'Let\'s Encrypt',
|
||||
zerossl: 'ZeroSSL',
|
||||
custom: 'Custom directory URL',
|
||||
}
|
||||
import { PROVIDER_LABELS } from './https.ts'
|
||||
|
||||
/** The problem of a custom ACME directory URL, or ''. */
|
||||
function urlProblem(value: string) {
|
||||
|
||||
+6
-20
@@ -2,7 +2,6 @@ import AccountCircle from '@mui/icons-material/AccountCircle'
|
||||
import EditNote from '@mui/icons-material/EditNote'
|
||||
import HelpOutline from '@mui/icons-material/HelpOutlineOutlined'
|
||||
import Logout from '@mui/icons-material/Logout'
|
||||
import Terminal from '@mui/icons-material/Terminal'
|
||||
import { Box, Button, CircularProgress, Container, IconButton, Link, Stack, Tab, Tabs, Tooltip, Typography } from '@mui/material'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import AccountPanel from './AccountPanel.tsx'
|
||||
@@ -44,7 +43,7 @@ type SitesView = 'sites' | 'files'
|
||||
/** The help topic of each tab of the Web Sites page. */
|
||||
const SITES_TOPICS: Record<SitesView, string> = { sites: 'sites.md', files: 'site-files.md' }
|
||||
|
||||
/** The prefix of the sessionStorage keys of the pages the account and the shell page were opened from, by their paths. */
|
||||
/** The prefix of the sessionStorage key of the page the account page was opened from, by its path. */
|
||||
const RETURN_KEY = 'linux-manager-ui.return:'
|
||||
|
||||
/** The pages of an administrator besides Router, which every other path shows. */
|
||||
@@ -71,11 +70,10 @@ const HELP_KEY = 'linux-manager-ui.help'
|
||||
* WireGuard access; at CA_PATH its certificates; at SITES_PATH its web
|
||||
* sites and the files of a site, opened from the sites too; at DNS_PATH its name server, while it is on; at DOCKER_PATH the state of Docker; at SHELL_PATH a shell on the server; otherwise the state of the server, with the update information of its packages in
|
||||
* the Status panel, its metrics, its logs, its backups or the updates of its system's packages. A page shows one tab at a time, each read only while shown. An
|
||||
* administrator switches pages with the page menu at the right end of the header; the button with the user's name,
|
||||
* left of Sign out, opens the user's own account, and an administrator's shell button, left of it, the shell; pressed
|
||||
* on their page, each returns to the page it was opened from; with the browser setting shellNewTab the shell button opens
|
||||
* the shell in a new tab instead. While files are open in the shell's editor, the editor
|
||||
* button left of the shell button switches the Shell page between the terminal and the editor. The help button, between the theme switcher and the page menu, opens or closes the help on
|
||||
* administrator switches pages with the page menu at the right end of the header, whose Shell entry opens the shell in
|
||||
* a new tab with the browser setting shellNewTab; the button with the user's name, left of Sign out, opens the user's
|
||||
* own account, and pressed on it returns to the page it was opened from. While files are open in the shell's editor, the
|
||||
* editor button left of the user's name switches the Shell page between the terminal and the editor. The help button, between the theme switcher and the page menu, opens or closes the help on
|
||||
* the right (HelpPanel) at the topic of the page and tab shown (HELP_TOPICS), the page moving left; the browser keeps
|
||||
* whether it is open. A call answered 401 ends the session and asks for a sign-in again.
|
||||
*/
|
||||
@@ -219,18 +217,6 @@ export default function App(props: { info: Info }) {
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
{session && admin && (
|
||||
<Tooltip title={page === SHELL_PATH ? 'Back from the shell' : 'Shell'}>
|
||||
<IconButton
|
||||
aria-label="shell"
|
||||
color={page === SHELL_PATH ? 'primary' : 'default'}
|
||||
onClick={() => (shellNewTab && page !== SHELL_PATH ? window.open(SHELL_PATH, '_blank') : toggle(SHELL_PATH))}
|
||||
sx={page === SHELL_PATH ? { bgcolor: 'action.selected' } : undefined}
|
||||
>
|
||||
<Terminal />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
{session && (
|
||||
<>
|
||||
<Button variant={userPage ? 'contained' : 'outlined'} startIcon={<AccountCircle />} onClick={() => toggle(USER_PATH)} sx={{ textTransform: 'none' }}>
|
||||
@@ -254,7 +240,7 @@ export default function App(props: { info: Info }) {
|
||||
</Tooltip>
|
||||
)}
|
||||
{session && admin && (
|
||||
<PageMenu path={page} hidden={[...(vpnOff ? [REMOTE_ACCESS_PATH] : []), ...(dnsOff ? [DNS_PATH] : []), ...(dockerMissing ? [DOCKER_PATH] : [])]} />
|
||||
<PageMenu path={page} newTab={shellNewTab ? [SHELL_PATH] : []} hidden={[...(vpnOff ? [REMOTE_ACCESS_PATH] : []), ...(dnsOff ? [DNS_PATH] : []), ...(dockerMissing ? [DOCKER_PATH] : [])]} />
|
||||
)}
|
||||
</Stack>
|
||||
</Stack>
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
TextField, Typography,
|
||||
} from '@mui/material'
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import { TARGET_LABELS } from './BackupSummary.tsx'
|
||||
import { TARGET_LABELS } from './backup.ts'
|
||||
import { BACKUP_KEEPS, BACKUP_SCHEDULES, BACKUP_TARGETS, RCLONE_MODES, type Backup, type BackupKeep, type BackupSettings } from './api.ts'
|
||||
|
||||
/** The labels of the retention settings. */
|
||||
|
||||
+13
-8
@@ -4,10 +4,15 @@ import Refresh from '@mui/icons-material/Refresh'
|
||||
import { Alert, Box, Button, Table, TableBody, TableCell, TableHead, TablePagination, TableRow } from '@mui/material'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import BackupDialog from './BackupDialog.tsx'
|
||||
import { BackupChip, TARGET_LABELS, backupRows, when } from './BackupSummary.tsx'
|
||||
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { Pairs, bytes } from './ServerPanel.tsx'
|
||||
import SearchField, { matches } from './SearchField.tsx'
|
||||
import { BackupChip } from './BackupSummary.tsx'
|
||||
import { backupRows, TARGET_LABELS } from './backup.ts'
|
||||
import { when } from './format.ts'
|
||||
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { useBoard } from './useBoard.ts'
|
||||
import { Pairs } from './ServerPanel.tsx'
|
||||
import { bytes } from './format.ts'
|
||||
import SearchField from './SearchField.tsx'
|
||||
import { matches } from './search.ts'
|
||||
import Toolbar from './Toolbar.tsx'
|
||||
import { ApiError, BACKUP_KEEPS, BACKUP_SCHEDULES, BACKUP_SETTINGS_SHAPE, BACKUP_SHAPE, STARTED_SHAPE, request, type Backup } from './api.ts'
|
||||
|
||||
@@ -41,22 +46,22 @@ export default function BackupPanel() {
|
||||
// The start of the last run when Run now was pressed; watching ends once a later run has ended.
|
||||
const startedBefore = useRef<string | null>(null)
|
||||
|
||||
/** Reads the backups; the state changes only once the server answers. */
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const found = await request<Backup>('GET', '/backup', BACKUP_SHAPE)
|
||||
await request<Backup>('GET', '/backup', BACKUP_SHAPE).then((found) => {
|
||||
setBackup(found)
|
||||
setError(null)
|
||||
setUnavailable(false)
|
||||
if (found.state && found.state.result !== 'running' && found.state.started !== startedBefore.current) {
|
||||
setWatching(false)
|
||||
}
|
||||
} catch (caught) {
|
||||
}, (caught) => {
|
||||
const failure = caught as ApiError
|
||||
setBackup(null)
|
||||
setUnavailable(failure.status === 404)
|
||||
setError(failure.message)
|
||||
setWatching(false)
|
||||
}
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Chip } from '@mui/material'
|
||||
import { bytes } from './ServerPanel.tsx'
|
||||
import type { Backup, BackupState } from './api.ts'
|
||||
import type { BackupState } from './api.ts'
|
||||
|
||||
/** The colour of each result of a backup run. */
|
||||
const RESULT_COLORS: Record<string, 'success' | 'warning' | 'error' | 'info'> = {
|
||||
@@ -11,43 +10,9 @@ const RESULT_COLORS: Record<string, 'success' | 'warning' | 'error' | 'info'> =
|
||||
running: 'info',
|
||||
}
|
||||
|
||||
/** The labels of the backup targets. */
|
||||
export const TARGET_LABELS: Record<string, string> = { local: 'Local folder', pbs: 'Proxmox Backup Server' }
|
||||
|
||||
/** A time of the server in the browser's format, or a dash. */
|
||||
export function when(time: string | null | undefined) {
|
||||
return time ? new Date(time).toLocaleString() : '-'
|
||||
}
|
||||
|
||||
/** The result of the last backup run as a chip, or "never" before the first. */
|
||||
export function BackupChip(props: { state: BackupState | null }) {
|
||||
return props.state
|
||||
? <Chip size="small" label={props.state.result} color={RESULT_COLORS[props.state.result] ?? 'default'} />
|
||||
: <Chip size="small" label="never" variant="outlined" />
|
||||
}
|
||||
|
||||
/** The schedule, the next run (as systemd shows it) and the last run of the server's backups, as rows of Pairs. */
|
||||
export function backupRows(backup: Backup): [string, string][] {
|
||||
const { settings, state } = backup
|
||||
const rows: [string, string][] = [
|
||||
['Backups', settings.enabled ? `${settings.schedule}, to ${TARGET_LABELS[settings.target] ?? settings.target}` : 'off'],
|
||||
['Next run', backup.next ?? '-'],
|
||||
]
|
||||
if (!state) {
|
||||
return [...rows, ['Last run', 'none']]
|
||||
}
|
||||
rows.push(
|
||||
['Last run', `${when(state.started)}${state.finished ? ` to ${new Date(state.finished).toLocaleTimeString()}` : ''}`],
|
||||
['Last result', state.result],
|
||||
)
|
||||
if (state.archive ?? state.snapshot) {
|
||||
rows.push(['Last backup', `${state.archive ?? state.snapshot}${state.size === null ? '' : `, ${bytes(state.size)}`}`])
|
||||
}
|
||||
if (state.cloud) {
|
||||
rows.push(['Cloud copy', `${state.cloud.mode} to ${state.cloud.remote}: ${state.cloud.error ?? state.cloud.result}`])
|
||||
}
|
||||
if (state.error) {
|
||||
rows.push(['Error', state.error])
|
||||
}
|
||||
return rows
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
Tooltip, Typography,
|
||||
} from '@mui/material'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { when } from './BackupSummary.tsx'
|
||||
import { when } from './format.ts'
|
||||
import CertificateDialog from './CertificateDialog.tsx'
|
||||
import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
|
||||
import ImportDialog from './ImportDialog.tsx'
|
||||
@@ -20,8 +20,10 @@ import IssuingCaDialog from './IssuingCaDialog.tsx'
|
||||
import TemplateDialog from './TemplateDialog.tsx'
|
||||
import Toolbar from './Toolbar.tsx'
|
||||
import EkuDialog from './EkuDialog.tsx'
|
||||
import PkiSettingsDialog, { PUBLISH_LABELS, ROOT_SOURCE_LABELS } from './PkiSettingsDialog.tsx'
|
||||
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
|
||||
import PkiSettingsDialog from './PkiSettingsDialog.tsx'
|
||||
import { ROOT_SOURCE_LABELS } from './pki.ts'
|
||||
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { useBoard } from './useBoard.ts'
|
||||
import { Pairs, Section } from './ServerPanel.tsx'
|
||||
import ServerCertificatePanel from './ServerCertificatePanel.tsx'
|
||||
import SetupCodeDialog from './SetupCodeDialog.tsx'
|
||||
@@ -89,7 +91,7 @@ export default function CertificatesPanel() {
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [unavailable, setUnavailable] = useState(false)
|
||||
const [note, setNote] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [busy, setBusy] = useState(true)
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [authority, setAuthority] = useState<{ name?: string } | null>(null)
|
||||
const [template, setTemplate] = useState<{ name?: string } | null>(null)
|
||||
@@ -105,25 +107,31 @@ export default function CertificatesPanel() {
|
||||
const rootBoard = useBoard(ROOT_LAYOUT_KEY)
|
||||
const issuingBoard = useBoard(ISSUING_LAYOUT_KEY)
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
setPki(await request<Pki>('GET', '/ca', PKI_SHAPE))
|
||||
setError(null)
|
||||
setUnavailable(false)
|
||||
} catch (caught) {
|
||||
const failure = caught as ApiError
|
||||
setPki(null)
|
||||
setUnavailable(failure.status === 404)
|
||||
setError(failure.message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
/** Reads the PKI; the state changes only once the server answers. */
|
||||
const read = useCallback(async () => {
|
||||
await request<Pki>('GET', '/ca', PKI_SHAPE)
|
||||
.then((found) => {
|
||||
setPki(found)
|
||||
setError(null)
|
||||
setUnavailable(false)
|
||||
}, (caught) => {
|
||||
const failure = caught as ApiError
|
||||
setPki(null)
|
||||
setUnavailable(failure.status === 404)
|
||||
setError(failure.message)
|
||||
})
|
||||
.finally(() => setBusy(false))
|
||||
}, [])
|
||||
|
||||
/** Reads the PKI again, busy until the server answers. */
|
||||
const refresh = useCallback(() => {
|
||||
setBusy(true)
|
||||
return read()
|
||||
}, [read])
|
||||
|
||||
useEffect(() => {
|
||||
void refresh()
|
||||
}, [refresh])
|
||||
void read()
|
||||
}, [read])
|
||||
|
||||
/** Saves the certificates a client trusts the CA with: the root alone, or an issuing CA followed by the root. */
|
||||
async function downloadBundle(name: string) {
|
||||
@@ -370,7 +378,7 @@ export default function CertificatesPanel() {
|
||||
<Pairs
|
||||
rows={[
|
||||
['Source', root.source === 'simple-ca' ? `Simple CA, ${root.simple_ca_url}` : ROOT_SOURCE_LABELS[root.source]],
|
||||
['State', <Chip size="small" label={root.state} color={STATE_COLORS[root.state] ?? 'default'} />],
|
||||
['State', <Chip key="state" size="small" label={root.state} color={STATE_COLORS[root.state] ?? 'default'} />],
|
||||
['Subject', root.subject ?? '-'],
|
||||
['Expires', when(root.expires)],
|
||||
['CRL valid until', when(root.crl_next_update)],
|
||||
@@ -419,7 +427,6 @@ export default function CertificatesPanel() {
|
||||
content: (
|
||||
<Pairs
|
||||
rows={[
|
||||
['Published at', pki.settings.publish.map((item) => PUBLISH_LABELS[item] ?? item).join('; ') || 'nowhere'],
|
||||
['CA key', pki.settings.key],
|
||||
['Lifetimes', `root ${pki.settings.root_days} days, issuing CAs ${pki.settings.ca_days} days`],
|
||||
['CRLs', `issuing CAs ${pki.settings.crl_days} days, root ${pki.settings.root_crl_days} days`],
|
||||
|
||||
@@ -40,11 +40,10 @@ export default function ComponentsPanel(props: { onChange?: () => void }) {
|
||||
const [router, setRouter] = useState<Component | null>(null)
|
||||
|
||||
const read = useCallback(async () => {
|
||||
try {
|
||||
setComponents((await request<{ components: Component[] }>('GET', '/components', COMPONENTS_SHAPE)).components)
|
||||
} catch (caught) {
|
||||
setError(`The server did not give its components: ${(caught as Error).message}`)
|
||||
}
|
||||
await request<{ components: Component[] }>('GET', '/components', COMPONENTS_SHAPE).then(
|
||||
(found) => setComponents(found.components),
|
||||
(caught) => setError(`The server did not give its components: ${(caught as Error).message}`),
|
||||
)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
+25
-18
@@ -9,7 +9,8 @@ import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
|
||||
import DnsDomainDialog from './DnsDomainDialog.tsx'
|
||||
import DnsRecordDialog from './DnsRecordDialog.tsx'
|
||||
import DnsSettingsDialog from './DnsSettingsDialog.tsx'
|
||||
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { useBoard } from './useBoard.ts'
|
||||
import { Pairs } from './ServerPanel.tsx'
|
||||
import Toolbar from './Toolbar.tsx'
|
||||
import {
|
||||
@@ -72,7 +73,7 @@ export default function DnsPanel() {
|
||||
const [dns, setDns] = useState<Dns | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [unavailable, setUnavailable] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [busy, setBusy] = useState(true)
|
||||
const [settings, setSettings] = useState(false)
|
||||
const [selected, setSelected] = useState<string | null>(null)
|
||||
const [editing, setEditing] = useState<DnsDomain | 'new' | null>(null)
|
||||
@@ -80,25 +81,31 @@ export default function DnsPanel() {
|
||||
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
|
||||
const board = useBoard(LAYOUT_KEY)
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
setDns(await request<Dns>('GET', '/dns', DNS_SHAPE))
|
||||
setError(null)
|
||||
setUnavailable(false)
|
||||
} catch (caught) {
|
||||
const failure = caught as ApiError
|
||||
setDns(null)
|
||||
setUnavailable(failure.status === 404)
|
||||
setError(failure.message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
/** Reads the name server's state; the state changes only once the server answers. */
|
||||
const read = useCallback(async () => {
|
||||
await request<Dns>('GET', '/dns', DNS_SHAPE)
|
||||
.then((found) => {
|
||||
setDns(found)
|
||||
setError(null)
|
||||
setUnavailable(false)
|
||||
}, (caught) => {
|
||||
const failure = caught as ApiError
|
||||
setDns(null)
|
||||
setUnavailable(failure.status === 404)
|
||||
setError(failure.message)
|
||||
})
|
||||
.finally(() => setBusy(false))
|
||||
}, [])
|
||||
|
||||
/** Reads the name server's state again, busy until the server answers. */
|
||||
const refresh = useCallback(() => {
|
||||
setBusy(true)
|
||||
return read()
|
||||
}, [read])
|
||||
|
||||
useEffect(() => {
|
||||
void refresh()
|
||||
}, [refresh])
|
||||
void read()
|
||||
}, [read])
|
||||
|
||||
/** Ask for a confirmation, then send the removal and refresh. */
|
||||
function confirmRemove(title: string, message: string, send: () => Promise<unknown>) {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import Refresh from '@mui/icons-material/Refresh'
|
||||
import { Alert, Box, Button, Typography } from '@mui/material'
|
||||
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { Pairs, text } from './ServerPanel.tsx'
|
||||
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { useBoard } from './useBoard.ts'
|
||||
import { Pairs } from './ServerPanel.tsx'
|
||||
import { text } from './format.ts'
|
||||
import Toolbar from './Toolbar.tsx'
|
||||
import { DETAILS_SHAPE, STATUS_SHAPE, request, type RouterDetails, type RouterStatus } from './api.ts'
|
||||
import { useRead } from './useRead.ts'
|
||||
|
||||
+30
-24
@@ -9,7 +9,8 @@ import { useCallback, useEffect, useState } from 'react'
|
||||
import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
|
||||
import GroupDialog from './GroupDialog.tsx'
|
||||
import { Section } from './ServerPanel.tsx'
|
||||
import SearchField, { matches } from './SearchField.tsx'
|
||||
import SearchField from './SearchField.tsx'
|
||||
import { matches } from './search.ts'
|
||||
import Toolbar from './Toolbar.tsx'
|
||||
import { ApiError, GROUPS_SHAPE, GROUP_SHAPE, REMOVED_SHAPE, SERVICE_ACCOUNTS_SHAPE, USERS_SHAPE, request, type Group, type User } from './api.ts'
|
||||
|
||||
@@ -23,37 +24,42 @@ export default function GroupsPanel() {
|
||||
const [users, setUsers] = useState<string[]>([])
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [unavailable, setUnavailable] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [busy, setBusy] = useState(true)
|
||||
const [adding, setAdding] = useState(false)
|
||||
const [editing, setEditing] = useState<Group | null>(null)
|
||||
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
|
||||
const [search, setSearch] = useState('')
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const [found, people, services] = await Promise.all([
|
||||
request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE),
|
||||
request<{ users: User[] }>('GET', '/users', USERS_SHAPE),
|
||||
request<{ service_accounts: User[] }>('GET', '/service-accounts', SERVICE_ACCOUNTS_SHAPE),
|
||||
])
|
||||
setGroups(found.groups)
|
||||
setUsers([...people.users, ...services.service_accounts.filter((account) => !account.internal)].map((user) => user.name).sort())
|
||||
setError(null)
|
||||
setUnavailable(false)
|
||||
} catch (caught) {
|
||||
const failure = caught as ApiError
|
||||
setGroups(null)
|
||||
setUnavailable(failure.status === 404)
|
||||
setError(failure.message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
/** Reads the groups with the users and service accounts; the state changes only once the server answers. */
|
||||
const read = useCallback(async () => {
|
||||
await Promise.all([
|
||||
request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE),
|
||||
request<{ users: User[] }>('GET', '/users', USERS_SHAPE),
|
||||
request<{ service_accounts: User[] }>('GET', '/service-accounts', SERVICE_ACCOUNTS_SHAPE),
|
||||
])
|
||||
.then(([found, people, services]) => {
|
||||
setGroups(found.groups)
|
||||
setUsers([...people.users, ...services.service_accounts.filter((account) => !account.internal)].map((user) => user.name).sort())
|
||||
setError(null)
|
||||
setUnavailable(false)
|
||||
}, (caught) => {
|
||||
const failure = caught as ApiError
|
||||
setGroups(null)
|
||||
setUnavailable(failure.status === 404)
|
||||
setError(failure.message)
|
||||
})
|
||||
.finally(() => setBusy(false))
|
||||
}, [])
|
||||
|
||||
/** Reads the groups again, busy until the server answers. */
|
||||
const refresh = useCallback(() => {
|
||||
setBusy(true)
|
||||
return read()
|
||||
}, [read])
|
||||
|
||||
useEffect(() => {
|
||||
void refresh()
|
||||
}, [refresh])
|
||||
void read()
|
||||
}, [read])
|
||||
|
||||
/** Runs a change of a group, then reads the list again; a failure is shown above the list. */
|
||||
async function change(work: () => Promise<unknown>) {
|
||||
|
||||
@@ -71,16 +71,18 @@ export default function HelpPanel(props: { open: boolean; topic: string; onClose
|
||||
const { mode, systemMode } = useColorScheme()
|
||||
const scheme = (mode === 'system' ? systemMode : mode) === 'dark' ? 'dark' : 'light'
|
||||
const [history, setHistory] = useState<string[]>([props.topic])
|
||||
const [topic, setTopic] = useState(props.topic)
|
||||
const [title, setTitle] = useState('Help')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const content = useRef<HTMLDivElement>(null)
|
||||
// A new topic starts the history again.
|
||||
if (topic !== props.topic) {
|
||||
setTopic(props.topic)
|
||||
setHistory([props.topic])
|
||||
}
|
||||
const current = history[history.length - 1]
|
||||
const [path, anchor] = current.split('#')
|
||||
|
||||
useEffect(() => {
|
||||
setHistory([props.topic])
|
||||
}, [props.topic])
|
||||
|
||||
useEffect(() => {
|
||||
if (!props.open) {
|
||||
return
|
||||
|
||||
@@ -1,21 +1,15 @@
|
||||
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography } from '@mui/material'
|
||||
import { Alert, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, MenuItem, Stack, TextField, Typography } from '@mui/material'
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import { HTTPS_CERTIFICATES, type HttpsCertificateSource, type HttpsChange, type HttpsSettings } from './api.ts'
|
||||
|
||||
/** The labels of the sources of the server's certificate. */
|
||||
export const CERTIFICATE_LABELS: Record<HttpsCertificateSource, string> = {
|
||||
acme: 'ACME',
|
||||
'self-signed': 'Self-signed',
|
||||
ca: 'Servers Issuing CA of the server\'s PKI',
|
||||
external: 'Another CA: a CSR signed there, or a PFX',
|
||||
}
|
||||
import { CERTIFICATE_LABELS } from './https.ts'
|
||||
|
||||
/**
|
||||
* A dialog that edits where the certificate of the server's FQDN comes from, https.certificate: the ACME CA of
|
||||
* A dialog that edits where the certificate of the server's HTTPS names comes from, https.certificate: the ACME CA of
|
||||
* AcmeSettingsDialog, a self-signed certificate valid for https.self_signed_days, the Servers Issuing CA, or another
|
||||
* CA's certificate, imported on the Server tab of the Certificates page; self-signed is selected while the first setup
|
||||
* has not chosen one. onSave sends the source and the validity
|
||||
* only; the dialog closes when it succeeds and shows the server's message when it fails.
|
||||
* has not chosen one. Without ACME, https.ip_sans adds the server's addresses to the self-signed certificate and the
|
||||
* Servers Issuing CA's. onSave sends the source, the validity and ip_sans only; the dialog closes when it succeeds and
|
||||
* shows the server's message when it fails.
|
||||
*/
|
||||
export default function HttpsSettingsDialog(props: {
|
||||
current: HttpsSettings
|
||||
@@ -24,6 +18,7 @@ export default function HttpsSettingsDialog(props: {
|
||||
}) {
|
||||
const [certificate, setCertificate] = useState<HttpsCertificateSource>(props.current.certificate || 'self-signed')
|
||||
const [days, setDays] = useState(String(props.current.self_signed_days))
|
||||
const [ipSans, setIpSans] = useState(props.current.ip_sans)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
@@ -38,7 +33,8 @@ export default function HttpsSettingsDialog(props: {
|
||||
setSaving(true)
|
||||
setError(null)
|
||||
try {
|
||||
await props.onSave(certificate === 'self-signed' ? { certificate, self_signed_days: Number(days) } : { certificate })
|
||||
await props.onSave(certificate === 'self-signed' ? { certificate, self_signed_days: Number(days), ip_sans: ipSans }
|
||||
: certificate === 'acme' ? { certificate } : { certificate, ip_sans: ipSans })
|
||||
} catch (caught) {
|
||||
setError((caught as Error).message)
|
||||
setSaving(false)
|
||||
@@ -69,6 +65,12 @@ export default function HttpsSettingsDialog(props: {
|
||||
onChange={(event) => setDays(event.target.value.trim())}
|
||||
/>
|
||||
)}
|
||||
{(certificate === 'self-signed' || certificate === 'ca') && (
|
||||
<FormControlLabel
|
||||
control={<Checkbox checked={ipSans} onChange={(event) => setIpSans(event.target.checked)} />}
|
||||
label="Also name the server's IP addresses, to reach it over HTTPS by address"
|
||||
/>
|
||||
)}
|
||||
{certificate === 'external' && (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
The certificate is imported on this tab, from a CSR the server makes or as a PFX file. The server serves a self-signed certificate until then.
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
Alert, Autocomplete, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Stack, Switch, TextField, Typography,
|
||||
} from '@mui/material'
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import { NAME_PATTERN, RESERVED, made, nameProblem } from './PkiSettingsDialog.tsx'
|
||||
import { made, NAME_PATTERN, nameProblem, RESERVED } from './pki.ts'
|
||||
import { ROUTER_TEMPLATES, type Pki, type PkiIssuingCa } from './api.ts'
|
||||
|
||||
/**
|
||||
|
||||
+33
-18
@@ -38,25 +38,40 @@ export default function LogsPanel() {
|
||||
.catch((caught) => setError((caught as Error).message))
|
||||
}, [])
|
||||
|
||||
const read = useCallback(async () => {
|
||||
if (kind === 'file' && !file) {
|
||||
setLines(null)
|
||||
return
|
||||
}
|
||||
setBusy(true)
|
||||
const query = kind === 'journal'
|
||||
// The query of the log chosen, null while the Files tab has no file.
|
||||
const query = kind === 'file' && !file
|
||||
? null
|
||||
: kind === 'journal'
|
||||
? `/logs/journal?lines=${count}${unit ? `&unit=${encodeURIComponent(unit)}` : ''}`
|
||||
: `/logs/file?lines=${count}&path=${encodeURIComponent(file)}`
|
||||
try {
|
||||
setLines((await request<{ lines: string[] }>('GET', query, LOG_LINES_SHAPE)).lines)
|
||||
setError(null)
|
||||
} catch (caught) {
|
||||
setLines(null)
|
||||
setError((caught as Error).message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
// The query whose answer is shown.
|
||||
const [shown, setShown] = useState<string | null>(null)
|
||||
const reading = busy || (sources !== null && query !== null && shown !== query)
|
||||
|
||||
/** Reads the log chosen; the state changes only once the server answers. */
|
||||
const read = useCallback(async () => {
|
||||
if (query === null) {
|
||||
return
|
||||
}
|
||||
}, [kind, unit, file, count])
|
||||
await request<{ lines: string[] }>('GET', query, LOG_LINES_SHAPE)
|
||||
.then((found) => {
|
||||
setLines(found.lines)
|
||||
setError(null)
|
||||
}, (caught) => {
|
||||
setLines(null)
|
||||
setError((caught as Error).message)
|
||||
})
|
||||
.finally(() => {
|
||||
setShown(query)
|
||||
setBusy(false)
|
||||
})
|
||||
}, [query])
|
||||
|
||||
/** Reads the log again, busy until the server answers. */
|
||||
const refresh = useCallback(() => {
|
||||
setBusy(true)
|
||||
return read()
|
||||
}, [read])
|
||||
|
||||
useEffect(() => {
|
||||
if (sources) {
|
||||
@@ -104,13 +119,13 @@ export default function LogsPanel() {
|
||||
<VerticalAlignBottom fontSize="small" sx={{ mr: 0.5 }} />
|
||||
Follow
|
||||
</ToggleButton>
|
||||
<Button variant="outlined" startIcon={<Refresh />} disabled={busy || follow || !sources} onClick={() => void read()}>
|
||||
<Button variant="outlined" startIcon={<Refresh />} disabled={reading || follow || !sources} onClick={() => void refresh()}>
|
||||
Refresh
|
||||
</Button>
|
||||
</Toolbar>
|
||||
{error && <Alert severity="error" sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>}
|
||||
{kind === 'file' && sources && sources.files.length === 0 && <Alert severity="info" sx={{ mb: 2 }}>No log files are configured.</Alert>}
|
||||
<LogView lines={lines} empty={busy ? '(reading)' : '(no lines)'} maxHeight={600} follow={follow} />
|
||||
<LogView lines={query === null ? null : lines} empty={reading ? '(reading)' : '(no lines)'} maxHeight={600} follow={follow} />
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
+31
-16
@@ -4,8 +4,9 @@ import { Alert, Box, Button, Stack, ToggleButton, ToggleButtonGroup, Typography
|
||||
import { LineChart } from '@mui/x-charts/LineChart'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import MetricsSettingsDialog from './MetricsSettingsDialog.tsx'
|
||||
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { bytes } from './ServerPanel.tsx'
|
||||
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { useBoard } from './useBoard.ts'
|
||||
import { bytes } from './format.ts'
|
||||
import {
|
||||
METRICS_RANGES, METRICS_SETTINGS_SHAPE, METRICS_SHAPE, request, type Aggregate, type MetricsHistory, type MetricsRange,
|
||||
type MetricsSettings,
|
||||
@@ -74,6 +75,8 @@ export default function MetricsPanel() {
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [reading, setReading] = useState(true)
|
||||
const [at, setAt] = useState<Date | null>(null)
|
||||
// The end of the axis until the first read answers.
|
||||
const [opened] = useState(() => new Date())
|
||||
const [hidden, setHidden] = useState<Record<string, string[]>>(readHidden)
|
||||
const [settings, setSettings] = useState<(MetricsSettings & { otlp_password_set: boolean }) | null>(null)
|
||||
const [opening, setOpening] = useState(false)
|
||||
@@ -99,24 +102,31 @@ export default function MetricsPanel() {
|
||||
})
|
||||
}
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setReading(true)
|
||||
try {
|
||||
setHistory(await request<MetricsHistory>('GET', `/metrics/history?range=${range}`, METRICS_SHAPE))
|
||||
setError(null)
|
||||
} catch (caught) {
|
||||
setError(`The server did not give its metrics: ${(caught as Error).message}`)
|
||||
}
|
||||
setAt(new Date())
|
||||
setReading(false)
|
||||
/** Reads the metrics of the view; the state changes only once the server answers. */
|
||||
const read = useCallback(async () => {
|
||||
await request<MetricsHistory>('GET', `/metrics/history?range=${range}`, METRICS_SHAPE)
|
||||
.then((found) => {
|
||||
setHistory(found)
|
||||
setError(null)
|
||||
}, (caught) => setError(`The server did not give its metrics: ${(caught as Error).message}`))
|
||||
.finally(() => {
|
||||
setAt(new Date())
|
||||
setReading(false)
|
||||
})
|
||||
}, [range])
|
||||
|
||||
/** Reads the metrics again, reading until the server answers. */
|
||||
const refresh = useCallback(() => {
|
||||
setReading(true)
|
||||
return read()
|
||||
}, [read])
|
||||
|
||||
// A read at once and on every change of the view, then every metricsRefresh seconds of the browser's settings, unless
|
||||
// it is manual (0).
|
||||
const { metricsRefresh } = useBrowserSettings()
|
||||
useEffect(() => {
|
||||
void refresh()
|
||||
}, [refresh])
|
||||
void read()
|
||||
}, [read])
|
||||
useEffect(() => {
|
||||
if (metricsRefresh === 0) {
|
||||
return
|
||||
@@ -133,7 +143,7 @@ export default function MetricsPanel() {
|
||||
const tunnels = [...new Set(points.flatMap((point) => Object.keys(point.site_to_site)))].sort()
|
||||
const format = new Intl.DateTimeFormat(undefined, RANGES[range].format)
|
||||
// The axis spans the whole view, whatever part of it has data.
|
||||
const end = at ?? new Date()
|
||||
const end = at ?? opened
|
||||
const start = RANGES[range].start(end)
|
||||
|
||||
const percent = (value: number) => `${value.toFixed(1)} %`
|
||||
@@ -226,7 +236,12 @@ export default function MetricsPanel() {
|
||||
return (
|
||||
<Box component="section">
|
||||
<Stack direction="row" sx={{ mb: 2, alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
|
||||
<ToggleButtonGroup size="small" exclusive value={range} onChange={(_event, next: MetricsRange | null) => next && setRange(next)}>
|
||||
<ToggleButtonGroup size="small" exclusive value={range} onChange={(_event, next: MetricsRange | null) => {
|
||||
if (next) {
|
||||
setReading(true)
|
||||
setRange(next)
|
||||
}
|
||||
}}>
|
||||
{METRICS_RANGES.map((name) => <ToggleButton key={name} value={name}>{RANGES[name].label}</ToggleButton>)}
|
||||
</ToggleButtonGroup>
|
||||
<ToggleButtonGroup size="small" exclusive value={consolidation} onChange={(_event, next: Consolidation | null) => next && setConsolidation(next)}>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import Refresh from '@mui/icons-material/Refresh'
|
||||
import { Alert, Box, Button } from '@mui/material'
|
||||
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { Grid, Pairs, text } from './ServerPanel.tsx'
|
||||
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { useBoard } from './useBoard.ts'
|
||||
import { Grid, Pairs } from './ServerPanel.tsx'
|
||||
import { text } from './format.ts'
|
||||
import Toolbar from './Toolbar.tsx'
|
||||
import { DETAILS_SHAPE, request, type RouterDetails } from './api.ts'
|
||||
import { useRead } from './useRead.ts'
|
||||
|
||||
+14
-5
@@ -6,6 +6,7 @@ import People from '@mui/icons-material/People'
|
||||
import Public from '@mui/icons-material/Public'
|
||||
import ViewInAr from '@mui/icons-material/ViewInAr'
|
||||
import Router from '@mui/icons-material/Router'
|
||||
import Terminal from '@mui/icons-material/Terminal'
|
||||
import VerifiedUser from '@mui/icons-material/VerifiedUser'
|
||||
import VpnKey from '@mui/icons-material/VpnKey'
|
||||
import { Button, ListItemIcon, ListItemText, Menu, MenuItem } from '@mui/material'
|
||||
@@ -35,7 +36,7 @@ export const SITES_PATH = '/sites-manager'
|
||||
/** The path of the DNS page: the name server's settings, domains and records. */
|
||||
export const DNS_PATH = '/dns-manager'
|
||||
|
||||
/** The path of the shell page: a login shell on the server, opened with the shell button of the header, not the menu. */
|
||||
/** The path of the Shell page: a login shell on the server. */
|
||||
export const SHELL_PATH = '/shell'
|
||||
|
||||
/** The pages of an administrator in the menu: path, label and icon. */
|
||||
@@ -48,13 +49,15 @@ const PAGES: { path: string; label: string; icon: ReactNode }[] = [
|
||||
{ path: SITES_PATH, label: 'Web Sites', icon: <Public fontSize="small" /> },
|
||||
{ path: DNS_PATH, label: 'DNS', icon: <Dns fontSize="small" /> },
|
||||
{ path: DOCKER_PATH, label: 'Docker', icon: <ViewInAr fontSize="small" /> },
|
||||
{ path: SHELL_PATH, label: 'Shell', icon: <Terminal fontSize="small" /> },
|
||||
]
|
||||
|
||||
/**
|
||||
* A button naming the page shown, or Pages on the account and the shell page, whose menu opens the pages of an
|
||||
* administrator but those of hidden, the pages of a component switched off or of software the server does not have.
|
||||
* A button naming the page shown, or Pages on the account page, whose menu opens the pages of an administrator but
|
||||
* those of hidden, the pages of a component switched off or of software the server does not have; the pages of newTab
|
||||
* open in a new tab.
|
||||
*/
|
||||
export default function PageMenu(props: { path: string; hidden: string[] }) {
|
||||
export default function PageMenu(props: { path: string; hidden: string[]; newTab: string[] }) {
|
||||
const [anchor, setAnchor] = useState<HTMLElement | null>(null)
|
||||
const current = PAGES.find((page) => page.path === props.path) ?? { path: props.path, label: 'Pages', icon: <MenuIcon fontSize="small" /> }
|
||||
return (
|
||||
@@ -72,7 +75,13 @@ export default function PageMenu(props: { path: string; hidden: string[] }) {
|
||||
</Button>
|
||||
<Menu anchorEl={anchor} open={anchor !== null} onClose={() => setAnchor(null)}>
|
||||
{PAGES.filter((page) => !props.hidden.includes(page.path)).map((page) => (
|
||||
<MenuItem key={page.path} component="a" href={page.path} selected={page.path === current.path}>
|
||||
<MenuItem
|
||||
key={page.path}
|
||||
component="a"
|
||||
href={page.path}
|
||||
{...(props.newTab.includes(page.path) && page.path !== current.path ? { target: '_blank', rel: 'noreferrer' } : {})}
|
||||
selected={page.path === current.path}
|
||||
>
|
||||
<ListItemIcon>{page.icon}</ListItemIcon>
|
||||
<ListItemText>{page.label}</ListItemText>
|
||||
</MenuItem>
|
||||
|
||||
+2
-49
@@ -13,7 +13,8 @@ import {
|
||||
import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors, type DragEndEvent } from '@dnd-kit/core'
|
||||
import { SortableContext, arrayMove, rectSortingStrategy, sortableKeyboardCoordinates, useSortable } from '@dnd-kit/sortable'
|
||||
import { CSS } from '@dnd-kit/utilities'
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import type { BoardState, Layout } from './useBoard.ts'
|
||||
|
||||
/** Colours of the panel titles: brown in the light scheme, gold in the dark one. */
|
||||
const TITLE_LIGHT = '#8b4513'
|
||||
@@ -25,44 +26,6 @@ const TITLE_DARK = '#d4af37'
|
||||
*/
|
||||
export type BoardPanel = { id: string; title: string; actions?: ReactNode; content: ReactNode; wide?: boolean; fixed?: boolean }
|
||||
|
||||
/** The layout of a board: the order of the panel ids, the width chosen for a panel, and the hidden and the folded panels. */
|
||||
export type Layout = { order: string[]; widths: Record<string, 'wide' | 'single'>; hidden: string[]; folded: string[] }
|
||||
|
||||
const EMPTY: Layout = { order: [], widths: {}, hidden: [], folded: [] }
|
||||
|
||||
/** The layout kept in localStorage under key, or an empty one when there is none or it cannot be read. */
|
||||
function readLayout(key: string): Layout {
|
||||
try {
|
||||
const value: unknown = JSON.parse(window.localStorage.getItem(key) ?? 'null')
|
||||
if (value !== null && typeof value === 'object') {
|
||||
const stored = value as Partial<Layout>
|
||||
const strings = (items: unknown) => (Array.isArray(items) ? items.filter((item): item is string => typeof item === 'string') : [])
|
||||
return {
|
||||
order: strings(stored.order),
|
||||
widths: stored.widths !== null && typeof stored.widths === 'object' ? stored.widths : {},
|
||||
hidden: strings(stored.hidden),
|
||||
folded: strings(stored.folded),
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// A layout that cannot be read is replaced by the default.
|
||||
}
|
||||
return EMPTY
|
||||
}
|
||||
|
||||
/** The layout of a board kept in the browser's localStorage under key, and a function that changes and keeps it. */
|
||||
export function useLayout(key: string): [Layout, (change: (current: Layout) => Layout) => void] {
|
||||
const [layout, setLayout] = useState<Layout>(() => readLayout(key))
|
||||
function update(change: (current: Layout) => Layout) {
|
||||
setLayout((current) => {
|
||||
const next = change(current)
|
||||
window.localStorage.setItem(key, JSON.stringify(next))
|
||||
return next
|
||||
})
|
||||
}
|
||||
return [layout, update]
|
||||
}
|
||||
|
||||
/** The panels in the order of the layout; a panel the layout does not know yet comes after the known ones, in the given order. */
|
||||
function ordered(panels: BoardPanel[], layout: Layout) {
|
||||
const rank = (panel: BoardPanel) => {
|
||||
@@ -230,16 +193,6 @@ export function PanelsDialog(props: { open: boolean; panels: BoardPanel[]; layou
|
||||
)
|
||||
}
|
||||
|
||||
/** The state of a page's board: its layout kept in the browser under key, whether it is edited, and the Panels dialog. */
|
||||
export type BoardState = ReturnType<typeof useBoard>
|
||||
|
||||
export function useBoard(key: string) {
|
||||
const [layout, setLayout] = useLayout(key)
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [choosing, setChoosing] = useState(false)
|
||||
return { layout, setLayout, editing, setEditing, choosing, setChoosing }
|
||||
}
|
||||
|
||||
/** The buttons of a board: Edit layout, Done while editing, and Panels, which opens the Panels dialog. */
|
||||
export function BoardButtons(props: { board: BoardState }) {
|
||||
const { editing, setEditing, setChoosing } = props.board
|
||||
|
||||
@@ -1,72 +1,15 @@
|
||||
import {
|
||||
Alert, Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, MenuItem, Stack, TextField,
|
||||
Typography,
|
||||
Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography,
|
||||
} from '@mui/material'
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import { PKI_KEYS, PKI_PUBLISH, type Pki, type PkiAuthority, type PkiRootSource, type PkiSettings, type PkiTemplate } from './api.ts'
|
||||
|
||||
/** The labels of the publishing endpoints. */
|
||||
export const PUBLISH_LABELS: Record<string, string> = {
|
||||
http: 'HTTP on the status port, served by the web service',
|
||||
'http-80': 'HTTP on port 80, served by Caddy',
|
||||
https: 'HTTPS on the HTTPS status port, served by Caddy',
|
||||
'https-default': 'HTTPS on port 443, served by Caddy',
|
||||
}
|
||||
|
||||
/** The labels of the sources of the root CA. */
|
||||
export const ROOT_SOURCE_LABELS: Record<PkiRootSource, string> = {
|
||||
local: 'Created by the server',
|
||||
offline: 'Offline',
|
||||
'simple-ca': 'Simple CA',
|
||||
}
|
||||
|
||||
/** The name of an issuing CA or a template, as the server accepts it. */
|
||||
export const NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}$/
|
||||
|
||||
/** The names the issuing CAs of pki.issuing_cas cannot have. */
|
||||
export const RESERVED = ['root', 'upstream', 'p2s', 's2s', 'servers']
|
||||
|
||||
/** The longest common name of a CA, in characters. */
|
||||
const CA_NAME_MAX = 64
|
||||
|
||||
/** The longest lifetime the server accepts, in days. */
|
||||
const DAYS_MAX = 36500
|
||||
|
||||
/** A new template's options. */
|
||||
export const NEW_TEMPLATE: PkiTemplate = {
|
||||
key: 'rsa-3072', days: 365, key_usage: ['digital_signature'], extended_key_usage: [], subject: 'name', sans: [], policies: [],
|
||||
}
|
||||
|
||||
/** Whether an issuing CA has its certificate or its CSR, which fix its common name. */
|
||||
export function made(authority: PkiAuthority) {
|
||||
return authority.state === 'active' || authority.state === 'pending'
|
||||
}
|
||||
|
||||
/** A common name's problem, or ''. */
|
||||
export function nameProblem(value: string) {
|
||||
return value.trim() === '' || value.trim().length > CA_NAME_MAX ? `1 to ${CA_NAME_MAX} characters.` : ''
|
||||
}
|
||||
|
||||
/** The problem of the URL of a Simple CA service, or ''. */
|
||||
export function urlProblem(value: string) {
|
||||
try {
|
||||
const url = new URL(value.trim())
|
||||
return url.protocol === 'https:' && url.hostname !== '' && url.search === '' && url.hash === '' ? '' : 'An https:// URL.'
|
||||
} catch {
|
||||
return 'An https:// URL.'
|
||||
}
|
||||
}
|
||||
|
||||
/** A lifetime's problem, or ''. */
|
||||
export function daysProblem(value: number) {
|
||||
return !Number.isInteger(value) || value < 1 || value > DAYS_MAX ? `1 to ${DAYS_MAX} days.` : ''
|
||||
}
|
||||
import { PKI_KEYS, type Pki, type PkiSettings } from './api.ts'
|
||||
import { ROOT_SOURCE_LABELS, daysProblem, made, nameProblem, urlProblem } from './pki.ts'
|
||||
|
||||
/**
|
||||
* A dialog that edits the server's pki section but the general-purpose issuing CAs, the templates and the custom
|
||||
* extended key usages, which IssuingCaDialog, TemplateDialog and EkuDialog edit: the names of the P2S and site-to-site
|
||||
* CAs, the lifetimes and key type of the CAs, the validity of the CRLs, where certificates and CRLs are published and,
|
||||
* with a Simple CA root, the URL of the service. The source of the root is shown and not edited, as it is fixed once
|
||||
* CAs, the lifetimes and key type of the CAs, the validity of the CRLs and, with a Simple CA root, the URL of the
|
||||
* service. The source of the root is shown and not edited, as it is fixed once
|
||||
* the root exists. The root and the Servers CA are made by the first setup, so their names are not shown; the P2S and
|
||||
* site-to-site CAs are made when the VPN and the router are switched on, and their names are fixed from then on. The
|
||||
* server applies the lifetimes and key type when it creates a CA. onSave sends the settings; the dialog closes when it
|
||||
@@ -188,24 +131,6 @@ export default function PkiSettingsDialog(props: {
|
||||
onChange={(event) => change({ root_crl_days: number(event.target.value) })}
|
||||
/>
|
||||
</Stack>
|
||||
<Typography variant="subtitle2">Published certificates and CRLs</Typography>
|
||||
<Box>
|
||||
{PKI_PUBLISH.map((item) => (
|
||||
<FormControlLabel
|
||||
key={item}
|
||||
sx={{ display: 'flex' }}
|
||||
control={
|
||||
<Checkbox
|
||||
checked={settings.publish.includes(item)}
|
||||
onChange={(event) => change({
|
||||
publish: PKI_PUBLISH.filter((name) => (name === item ? event.target.checked : settings.publish.includes(name))),
|
||||
})}
|
||||
/>
|
||||
}
|
||||
label={PUBLISH_LABELS[item]}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
|
||||
@@ -3,12 +3,15 @@ import Edit from '@mui/icons-material/Edit'
|
||||
import Refresh from '@mui/icons-material/Refresh'
|
||||
import { Alert, Box, Button, Chip, Stack } from '@mui/material'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { useBoard } from './useBoard.ts'
|
||||
import RemoteAccessDialog from './RemoteAccessDialog.tsx'
|
||||
import Toolbar from './Toolbar.tsx'
|
||||
import WireGuardConfigDialog from './WireGuardConfigDialog.tsx'
|
||||
import WireGuardPeers from './WireGuardPeers.tsx'
|
||||
import { Copyable, Grid, IPSEC_HEADS, Pairs, bytes, ipsecRows, text } from './ServerPanel.tsx'
|
||||
import { Copyable, Grid, Pairs } from './ServerPanel.tsx'
|
||||
import { bytes, text } from './format.ts'
|
||||
import { IPSEC_HEADS, ipsecRows } from './ipsec.ts'
|
||||
import {
|
||||
DETAILS_SHAPE, REMOTE_ACCESS_LABELS, REMOTE_ACCESS_SECTION_SHAPES, REMOTE_ACCESS_SHAPE, STATUS_SHAPE, USERS_SHAPE, request,
|
||||
type RemoteAccess, type RemoteAccessSystem, type RouterDetails, type RouterStatus, type Users,
|
||||
@@ -41,7 +44,7 @@ export default function RemoteAccessPanel(props: { system: RemoteAccessSystem })
|
||||
const [access, setAccess] = useState<RemoteAccess | null>(null)
|
||||
const [status, setStatus] = useState<RouterStatus | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [busy, setBusy] = useState(true)
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [showConfig, setShowConfig] = useState(false)
|
||||
const board = useBoard(LAYOUT_KEYS[props.system])
|
||||
@@ -52,30 +55,33 @@ export default function RemoteAccessPanel(props: { system: RemoteAccessSystem })
|
||||
// IKEv2's: the server's details with its IPsec SAs and connections, those of IKEv2 access being all but site to site.
|
||||
const ikev2 = props.system === 'p2s'
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const [nextAccess, nextStatus, nextUsers, nextDetails] = await Promise.all([
|
||||
request<RemoteAccess>('GET', '/remote-access', REMOTE_ACCESS_SHAPE),
|
||||
request<RouterStatus>('GET', '/status/full', STATUS_SHAPE),
|
||||
wireguard ? request<Users>('GET', '/users', USERS_SHAPE) : null,
|
||||
wireguard || ikev2 ? request<RouterDetails>('GET', '/config', DETAILS_SHAPE) : null,
|
||||
])
|
||||
setAccess(nextAccess)
|
||||
setStatus(nextStatus)
|
||||
setUsers(nextUsers)
|
||||
setDetails(nextDetails)
|
||||
setError(null)
|
||||
} catch (caught) {
|
||||
setError((caught as Error).message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
/** Reads the access of the system with what it shows; the state changes only once the server answers. */
|
||||
const read = useCallback(async () => {
|
||||
await Promise.all([
|
||||
request<RemoteAccess>('GET', '/remote-access', REMOTE_ACCESS_SHAPE),
|
||||
request<RouterStatus>('GET', '/status/full', STATUS_SHAPE),
|
||||
wireguard ? request<Users>('GET', '/users', USERS_SHAPE) : null,
|
||||
wireguard || ikev2 ? request<RouterDetails>('GET', '/config', DETAILS_SHAPE) : null,
|
||||
])
|
||||
.then(([nextAccess, nextStatus, nextUsers, nextDetails]) => {
|
||||
setAccess(nextAccess)
|
||||
setStatus(nextStatus)
|
||||
setUsers(nextUsers)
|
||||
setDetails(nextDetails)
|
||||
setError(null)
|
||||
}, (caught) => setError((caught as Error).message))
|
||||
.finally(() => setBusy(false))
|
||||
}, [wireguard, ikev2])
|
||||
|
||||
/** Reads the access again, busy until the server answers. */
|
||||
const refresh = useCallback(() => {
|
||||
setBusy(true)
|
||||
return read()
|
||||
}, [read])
|
||||
|
||||
useEffect(() => {
|
||||
void refresh()
|
||||
}, [refresh])
|
||||
void read()
|
||||
}, [read])
|
||||
|
||||
async function save(settings: Record<string, unknown>) {
|
||||
await request('PUT', `/remote-access/${props.system}`, REMOTE_ACCESS_SECTION_SHAPES[props.system], settings)
|
||||
|
||||
@@ -14,9 +14,3 @@ export default function SearchField(props: { value: string; onChange: (value: st
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether any of the texts contains the search, ignoring case; an empty search matches everything. */
|
||||
export function matches(search: string, texts: (string | null | undefined)[]) {
|
||||
const wanted = search.trim().toLowerCase()
|
||||
return wanted === '' || texts.some((text) => text?.toLowerCase().includes(wanted))
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
import Settings from '@mui/icons-material/Settings'
|
||||
import { Alert, Box, Button, Chip, IconButton, Stack, Tooltip, Typography } from '@mui/material'
|
||||
import { useCallback, useEffect, useState, type ReactNode } from 'react'
|
||||
import AcmeSettingsDialog, { PROVIDER_LABELS } from './AcmeSettingsDialog.tsx'
|
||||
import { when } from './BackupSummary.tsx'
|
||||
import HttpsSettingsDialog, { CERTIFICATE_LABELS } from './HttpsSettingsDialog.tsx'
|
||||
import AcmeSettingsDialog from './AcmeSettingsDialog.tsx'
|
||||
import { PROVIDER_LABELS } from './https.ts'
|
||||
import { when } from './format.ts'
|
||||
import HttpsSettingsDialog from './HttpsSettingsDialog.tsx'
|
||||
import { CERTIFICATE_LABELS } from './https.ts'
|
||||
import ImportDialog from './ImportDialog.tsx'
|
||||
import PfxDialog from './PfxDialog.tsx'
|
||||
import { Pairs, Section, text } from './ServerPanel.tsx'
|
||||
import { Pairs, Section } from './ServerPanel.tsx'
|
||||
import { text } from './format.ts'
|
||||
import { saveFile } from './saveFile.ts'
|
||||
import {
|
||||
DETAILS_SHAPE, HTTPS_CSR_SHAPE, HTTPS_IMPORTED_SHAPE, HTTPS_SETTINGS_SHAPE, request, type HttpsCertificate, type HttpsChange,
|
||||
@@ -14,8 +17,8 @@ import {
|
||||
} from './api.ts'
|
||||
|
||||
/**
|
||||
* The Server tab of the Certificates page, the server's HTTPS from /config and /https/settings: whether HTTPS is on and
|
||||
* for which name, with a chip while the certificate has another source than ACME and a button that opens
|
||||
* The Server tab of the Certificates page, the server's HTTPS from /config and /https/settings: the names and addresses
|
||||
* HTTPS is served for, with a chip while the certificate has another source than ACME and a button that opens
|
||||
* HttpsSettingsDialog; the certificate of a source other than ACME, and, for one of another CA, Generate CSR, Import
|
||||
* certificate and Import PFX; the ACME CA with a chip while it is Let's Encrypt's staging environment and a button that
|
||||
* opens AcmeSettingsDialog; and Caddy, its version and the state of caddy.service. Until the first setup
|
||||
@@ -31,26 +34,29 @@ export default function ServerCertificatePanel() {
|
||||
const [settings, setSettings] = useState<{ dialog: 'https' | 'acme'; settings: HttpsSettings } | null>(null)
|
||||
const [importing, setImporting] = useState<'certificate' | 'pfx' | null>(null)
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setReading(true)
|
||||
try {
|
||||
const [nextDetails, nextHttps] = await Promise.all([
|
||||
request<RouterDetails>('GET', '/config', DETAILS_SHAPE),
|
||||
request<{ certificate?: HttpsCertificate }>('GET', '/https/settings', HTTPS_SETTINGS_SHAPE),
|
||||
])
|
||||
setDetails(nextDetails)
|
||||
setCertificate(nextHttps.certificate ?? null)
|
||||
setError(null)
|
||||
} catch (caught) {
|
||||
setError(`The server did not give its HTTPS settings: ${(caught as Error).message}`)
|
||||
} finally {
|
||||
setReading(false)
|
||||
}
|
||||
/** Reads the server's details and HTTPS certificate; the state changes only once the server answers. */
|
||||
const read = useCallback(async () => {
|
||||
await Promise.all([
|
||||
request<RouterDetails>('GET', '/config', DETAILS_SHAPE),
|
||||
request<{ certificate?: HttpsCertificate }>('GET', '/https/settings', HTTPS_SETTINGS_SHAPE),
|
||||
])
|
||||
.then(([nextDetails, nextHttps]) => {
|
||||
setDetails(nextDetails)
|
||||
setCertificate(nextHttps.certificate ?? null)
|
||||
setError(null)
|
||||
}, (caught) => setError(`The server did not give its HTTPS settings: ${(caught as Error).message}`))
|
||||
.finally(() => setReading(false))
|
||||
}, [])
|
||||
|
||||
/** Reads the details and the certificate again, reading until the server answers. */
|
||||
const refresh = useCallback(() => {
|
||||
setReading(true)
|
||||
return read()
|
||||
}, [read])
|
||||
|
||||
useEffect(() => {
|
||||
void refresh()
|
||||
}, [refresh])
|
||||
void read()
|
||||
}, [read])
|
||||
|
||||
/** Reads the server's https section from /https/settings and opens HttpsSettingsDialog or AcmeSettingsDialog with it. */
|
||||
async function open(dialog: 'https' | 'acme') {
|
||||
@@ -83,10 +89,9 @@ export default function ServerCertificatePanel() {
|
||||
}
|
||||
|
||||
const https = details?.configuration.https
|
||||
const fqdn = String(details?.configuration.wan?.local_fqdn ?? '')
|
||||
const httpsOn = https?.enabled === true
|
||||
const hosts = [...(details?.network.https_names ?? []), ...(details?.network.https_addresses ?? [])]
|
||||
const chosen = certificate !== null && certificate.source !== ''
|
||||
const other = httpsOn && certificate !== null && certificate.source !== 'acme'
|
||||
const other = certificate !== null && certificate.source !== 'acme'
|
||||
|
||||
return (
|
||||
<Box>
|
||||
@@ -100,9 +105,9 @@ export default function ServerCertificatePanel() {
|
||||
rows={[
|
||||
['HTTPS', (
|
||||
<Stack key="https" direction="row" sx={{ alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
|
||||
<span>{httpsOn ? (fqdn ? `on, for ${fqdn}` : 'on, but wan.local_fqdn is not set') : 'off'}</span>
|
||||
<span>{hosts.length > 0 ? `for ${hosts.join(', ')}` : 'on'}</span>
|
||||
{other && certificate.source !== '' && <Chip size="small" label={CERTIFICATE_LABELS[certificate.source]} color={certificate.served === certificate.source ? 'default' : 'warning'} />}
|
||||
{httpsOn && !chosen && <Typography variant="body2" color="text.secondary">certificate chosen by the next setup</Typography>}
|
||||
{!chosen && <Typography variant="body2" color="text.secondary">certificate chosen by the next setup</Typography>}
|
||||
<Tooltip title="HTTPS certificate">
|
||||
<IconButton size="small" aria-label="HTTPS certificate" onClick={() => void open('https')}>
|
||||
<Settings fontSize="small" />
|
||||
|
||||
+51
-125
@@ -3,14 +3,17 @@ import PlayArrow from '@mui/icons-material/PlayArrow'
|
||||
import Refresh from '@mui/icons-material/Refresh'
|
||||
import { Alert, Box, Button, Chip, IconButton, Link, Paper, Stack, Table, TableBody, TableCell, TableHead, TableRow, Tooltip, Typography } from '@mui/material'
|
||||
import { Fragment, useCallback, useEffect, useState, type ReactNode } from 'react'
|
||||
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { useBoard } from './useBoard.ts'
|
||||
import UpdatesNotice from './UpdatesNotice.tsx'
|
||||
import { BackupChip, backupRows } from './BackupSummary.tsx'
|
||||
import { BackupChip } from './BackupSummary.tsx'
|
||||
import { backupRows } from './backup.ts'
|
||||
import {
|
||||
ApiError, BACKUP_SHAPE, DETAILS_SHAPE, INFO_SHAPE, POSTGRESQL_SHAPE,
|
||||
STARTED_SHAPE, STATUS_SHAPE, request, type Backup, type Info, type PostgresqlDatabases,
|
||||
type RouterDetails, type RouterStatus,
|
||||
} from './api.ts'
|
||||
import { bytes, text } from './format.ts'
|
||||
import { useBrowserSettings } from './settings.ts'
|
||||
|
||||
/** The localStorage key of the tab's layout. */
|
||||
@@ -20,9 +23,9 @@ const LAYOUT_KEY = 'linux-manager-ui.router-layout'
|
||||
* The server's state: its status, ok or degraded on the title bar of the Status panel, with the update information of
|
||||
* its packages (UpdatesNotice) at the top of that panel, its remote access clients, and from /config the status web
|
||||
* service; the state of each of its systemd services and of Caddy in the Services panel; the Addresses panel's links
|
||||
* to the status page, over HTTPS for wan.local_fqdn and over plain HTTP on the addresses web.listen names, and to the
|
||||
* Manager over HTTPS, and over plain HTTP on the addresses of its listen from /api/info while Caddy does not redirect
|
||||
* it, each address once, and the
|
||||
* to the status page and the Manager over HTTPS for the HTTPS names and addresses, and over plain HTTP: the status page
|
||||
* on the addresses web.listen names, the Manager on the addresses of its listen from /api/info only while the redirect
|
||||
* to HTTPS is off, and both by their HTTPS names only while it is off, each address once, and the
|
||||
* OpenID Provider's issuer and discovery URL, each with a copy icon, or off while it is disabled; its
|
||||
* backups with Run now, and its non-public details as tables and command output, with a panel per PostgreSQL
|
||||
* cluster: its settings from /config and its databases with their sizes from /postgresql. Read at once, then as the
|
||||
@@ -44,10 +47,10 @@ export default function ServerPanel() {
|
||||
const board = useBoard(LAYOUT_KEY)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setReading(true)
|
||||
/** Reads the server's state; the state changes only once the server answers. */
|
||||
const read = useCallback(async () => {
|
||||
const found: { status?: string; details?: string; databases?: string; backup?: string } = {}
|
||||
const [nextStatus, nextDetails, nextDatabases, nextBackup, nextInfo] = await Promise.all([
|
||||
await Promise.all([
|
||||
request<RouterStatus>('GET', '/status/full', STATUS_SHAPE).catch((error: Error) => {
|
||||
found.status = `The server did not give its status: ${error.message}`
|
||||
return null
|
||||
@@ -67,24 +70,31 @@ export default function ServerPanel() {
|
||||
return null
|
||||
}),
|
||||
request<Info>('GET', '/info', INFO_SHAPE).catch(() => null),
|
||||
])
|
||||
setManager(nextInfo?.manager ?? null)
|
||||
setStatus(nextStatus)
|
||||
setDetails(nextDetails)
|
||||
setDatabases(nextDatabases)
|
||||
setBackup(nextBackup)
|
||||
setProblems(found)
|
||||
setReading(false)
|
||||
]).then(([nextStatus, nextDetails, nextDatabases, nextBackup, nextInfo]) => {
|
||||
setManager(nextInfo?.manager ?? null)
|
||||
setStatus(nextStatus)
|
||||
setDetails(nextDetails)
|
||||
setDatabases(nextDatabases)
|
||||
setBackup(nextBackup)
|
||||
setProblems(found)
|
||||
setReading(false)
|
||||
})
|
||||
}, [])
|
||||
|
||||
/** Reads the server's state again, reading until the server answers. */
|
||||
const refresh = useCallback(() => {
|
||||
setReading(true)
|
||||
return read()
|
||||
}, [read])
|
||||
|
||||
// A read at once and when a check for updates, an upgrade or a reboot ends, then every routerRefresh seconds of the
|
||||
// browser's settings, unless it is manual (0); nothing is read while one of them runs (busy).
|
||||
const { routerRefresh } = useBrowserSettings()
|
||||
useEffect(() => {
|
||||
if (!busy) {
|
||||
void refresh()
|
||||
void read()
|
||||
}
|
||||
}, [refresh, busy])
|
||||
}, [read, busy])
|
||||
useEffect(() => {
|
||||
if (routerRefresh === 0 || busy) {
|
||||
return
|
||||
@@ -96,18 +106,22 @@ export default function ServerPanel() {
|
||||
const network = details?.network
|
||||
const web = details?.configuration.web
|
||||
const https = details?.configuration.https
|
||||
const fqdn = String(details?.configuration.wan?.local_fqdn ?? '')
|
||||
const httpsOn = https?.enabled === true
|
||||
// The hosts HTTPS is served for: its names, then its addresses while https.ip_sans is on.
|
||||
const httpsNames = network?.https_names ?? []
|
||||
const httpsHosts = [...httpsNames, ...(network?.https_addresses ?? [])].map((host) => (host.includes(':') ? `[${host}]` : host))
|
||||
const redirectOff = https?.disable_auto_redirect === true
|
||||
const httpsUrls = (port: unknown) => httpsHosts.map((host) => `https://${host}:${text(port)}`)
|
||||
// A request by name on a plain HTTP port is redirected to HTTPS unless the redirect is off.
|
||||
const plainNames = (port: unknown) => (redirectOff ? httpsNames.map((name) => `http://${name}:${text(port)}`) : [])
|
||||
// The plain HTTP URLs of a port on the addresses of the interfaces a listen setting names, each address once: without
|
||||
// the router the internal address is the external one.
|
||||
const plainUrls = (listen: string, port: unknown) => [...new Set([
|
||||
...(listen !== 'external' && network?.internal_address ? [network.internal_address] : []),
|
||||
...(listen !== 'internal' ? network?.external_addresses ?? [] : []),
|
||||
].map((address) => String(address).split('/')[0]))].map((address) => `http://${address}:${text(port)}`)
|
||||
const plain = web?.enabled === false ? [] : plainUrls(String(web?.listen ?? 'both'), web?.port)
|
||||
// The Manager over plain HTTP while Caddy does not redirect it to HTTPS.
|
||||
const managerPlain = manager && (!httpsOn || !fqdn || https?.disable_auto_redirect === true)
|
||||
? plainUrls(manager.listen, manager.port) : []
|
||||
// The status page stays on plain HTTP by address; the Manager only while the redirect is off.
|
||||
const plain = web?.enabled === false ? [] : [...plainNames(web?.port), ...plainUrls(String(web?.listen ?? 'both'), web?.port)]
|
||||
const managerPlain = manager && redirectOff ? [...plainNames(manager.port), ...plainUrls(manager.listen, manager.port)] : []
|
||||
|
||||
// The panels in their default order; a panel without data is left out, and keeps its place in the layout.
|
||||
const panels: BoardPanel[] = []
|
||||
@@ -248,8 +262,8 @@ export default function ServerPanel() {
|
||||
content: (
|
||||
<Pairs
|
||||
rows={[
|
||||
['Status page', <Links key="status" urls={[...(httpsOn && fqdn ? [`https://${fqdn}:${text(https?.web_port)}`] : []), ...plain]} />],
|
||||
['Ubuntu Linux Manager', <Links key="manager" urls={[...(httpsOn && fqdn ? [`https://${fqdn}:${text(https?.manager_port)}`] : []), ...managerPlain]} />],
|
||||
['Status page', <Links key="status" urls={[...(web?.enabled === false ? [] : httpsUrls(https?.web_port)), ...plain]} />],
|
||||
['Ubuntu Linux Manager', <Links key="manager" urls={[...httpsUrls(https?.manager_port), ...managerPlain]} />],
|
||||
...(details.oidc?.issuer
|
||||
? [
|
||||
['OpenID Provider', <Copyable key="issuer" value={details.oidc.issuer} label="issuer" />],
|
||||
@@ -347,14 +361,6 @@ export default function ServerPanel() {
|
||||
)
|
||||
}
|
||||
|
||||
/** A value as text: lists joined with commas, an empty value as a dash. */
|
||||
export function text(value: unknown): string {
|
||||
if (Array.isArray(value)) {
|
||||
return value.length === 0 ? '-' : value.join(', ')
|
||||
}
|
||||
return value === undefined || value === null || value === '' ? '-' : String(value)
|
||||
}
|
||||
|
||||
/** The names shown for the server's systemd units; a unit not listed is shown by its unit name. */
|
||||
const UNIT_LABELS: Record<string, string> = {
|
||||
'linux-manager-setup': 'Linux Manager Setup',
|
||||
@@ -364,7 +370,6 @@ const UNIT_LABELS: Record<string, string> = {
|
||||
slapd: 'OpenLDAP',
|
||||
}
|
||||
|
||||
|
||||
/** Colours of the panel titles: brown in the light scheme, gold in the dark one. */
|
||||
const TITLE_LIGHT = '#8b4513'
|
||||
const TITLE_DARK = '#d4af37'
|
||||
@@ -399,16 +404,21 @@ export function Pairs(props: { rows: [string, string | ReactNode][] }) {
|
||||
)
|
||||
}
|
||||
|
||||
/** A value in monospace for Pairs with an action icon that puts it on the clipboard; label names it in the tooltip. */
|
||||
/**
|
||||
* A value in monospace for Pairs with an action icon that puts it on the clipboard, shown only on a page served over
|
||||
* HTTPS, where the browser offers the clipboard; label names it in the tooltip.
|
||||
*/
|
||||
export function Copyable(props: { value: string; label: string }) {
|
||||
return (
|
||||
<Stack direction="row" sx={{ alignItems: 'center', gap: 1 }}>
|
||||
<Box component="span" sx={{ fontFamily: 'monospace', fontSize: 13, wordBreak: 'break-all' }}>{props.value}</Box>
|
||||
<Tooltip title={`Copy the ${props.label}`}>
|
||||
<IconButton size="small" aria-label={`copy the ${props.label}`} onClick={() => void navigator.clipboard.writeText(props.value)}>
|
||||
<ContentCopy fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
{window.isSecureContext && (
|
||||
<Tooltip title={`Copy the ${props.label}`}>
|
||||
<IconButton size="small" aria-label={`copy the ${props.label}`} onClick={() => void navigator.clipboard.writeText(props.value)}>
|
||||
<ContentCopy fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
@@ -474,7 +484,6 @@ function Addressed(props: { text: string }) {
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
/** Whether a configuration section is in use: not switched off, and with at least one value set. */
|
||||
/** The headings of the sections of the configuration; a section not listed is headed by its name. */
|
||||
const SECTION_LABELS: Record<string, string> = {
|
||||
@@ -507,86 +516,3 @@ function Links(props: { urls: string[] }) {
|
||||
function sectionConfigured(values: Record<string, unknown>) {
|
||||
return values.enabled !== false && Object.values(values).some((value) => text(value) !== '-')
|
||||
}
|
||||
|
||||
/** The column titles of the IPsec tables of ipsecRows. */
|
||||
export const IPSEC_HEADS = {
|
||||
sas: ['Connection', 'State', 'Local', 'Remote', 'Algorithms', 'Up'],
|
||||
childSas: ['Child SA', 'State', 'Traffic selectors', 'In', 'Out', 'Up'],
|
||||
connections: ['Connection', 'Version', 'Local address', 'Local identity', 'Remote address', 'Remote identity', 'Authentication'],
|
||||
children: ['Child', 'Mode', 'Local traffic selectors', 'Remote traffic selectors'],
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows of the IPsec tables of the server's /config for the connections whose names keep accepts: the IKE SAs, their
|
||||
* child SAs, the connections and their children; undefined where the server could not list them.
|
||||
*/
|
||||
export function ipsecRows(details: RouterDetails | null, keep: (name: string) => boolean) {
|
||||
const sas = details?.ipsec.sas?.filter((sa) => keep(sa.name))
|
||||
const connections = details?.ipsec.connections?.filter((connection) => keep(connection.name))
|
||||
return {
|
||||
sas: sas?.map((sa) => [
|
||||
sa.name,
|
||||
sa.state,
|
||||
`${sa['local-id']} @ ${sa['local-host']}`,
|
||||
`${sa['remote-id']} @ ${sa['remote-host']}`,
|
||||
[`${text(sa['encr-alg'])}-${text(sa['encr-keysize'])}`, sa['integ-alg'], sa['dh-group']].filter(Boolean).join(', '),
|
||||
sa.established === undefined ? '-' : duration(Number(sa.established)),
|
||||
]),
|
||||
childSas: sas?.flatMap((sa) =>
|
||||
Object.values(sa['child-sas'] ?? {}).map((child) => [
|
||||
`${sa.name}/${child.name}`,
|
||||
`${child.state}, ${child.mode}`,
|
||||
`${child['local-ts'].join(', ')} <-> ${child['remote-ts'].join(', ')}`,
|
||||
`${bytes(Number(child['bytes-in']))}, ${child['packets-in']} packets`,
|
||||
`${bytes(Number(child['bytes-out']))}, ${child['packets-out']} packets`,
|
||||
child['install-time'] === undefined ? '-' : duration(Number(child['install-time'])),
|
||||
]),
|
||||
),
|
||||
connections: connections?.map((connection) => {
|
||||
const local = authOf(connection, 'local')
|
||||
const remote = authOf(connection, 'remote')
|
||||
return [
|
||||
connection.name,
|
||||
connection.version,
|
||||
text(connection.local_addrs),
|
||||
text(local.id),
|
||||
text(connection.remote_addrs),
|
||||
text(remote.id),
|
||||
local.class === remote.class ? text(local.class) : `${text(local.class)} / ${text(remote.class)}`,
|
||||
]
|
||||
}),
|
||||
children: connections?.flatMap((connection) =>
|
||||
Object.entries(connection.children ?? {}).map(([name, child]) => [
|
||||
`${connection.name}/${name}`,
|
||||
child.mode,
|
||||
child['local-ts'].join(', '),
|
||||
child['remote-ts'].join(', '),
|
||||
]),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/** The authentication round of one side of a connection: swanctl names them local-1, remote-1 and so on. */
|
||||
function authOf(connection: Record<string, unknown>, side: 'local' | 'remote'): { class?: string; id?: string } {
|
||||
const round = Object.entries(connection).find(([key, value]) => key.startsWith(`${side}-`) && typeof value === 'object' && value !== null)
|
||||
return (round?.[1] ?? {}) as { class?: string; id?: string }
|
||||
}
|
||||
|
||||
/** Seconds as "1h 2m 3s". */
|
||||
export function duration(seconds: number) {
|
||||
const h = Math.floor(seconds / 3600)
|
||||
const m = Math.floor((seconds % 3600) / 60)
|
||||
return [h && `${h}h`, (h || m) && `${m}m`, `${seconds % 60}s`].filter(Boolean).join(' ')
|
||||
}
|
||||
|
||||
/** Bytes in B, KiB, MiB or GiB. */
|
||||
export function bytes(count: number) {
|
||||
const units = ['B', 'KiB', 'MiB', 'GiB']
|
||||
let value = count
|
||||
let unit = 0
|
||||
while (value >= 1024 && unit < units.length - 1) {
|
||||
value /= 1024
|
||||
unit += 1
|
||||
}
|
||||
return `${unit === 0 ? value : value.toFixed(1)} ${units[unit]}`
|
||||
}
|
||||
@@ -10,7 +10,8 @@ import { Alert, Box, Button, IconButton, Table, TableBody, TableCell, TableHead,
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
|
||||
import { Section } from './ServerPanel.tsx'
|
||||
import SearchField, { matches } from './SearchField.tsx'
|
||||
import SearchField from './SearchField.tsx'
|
||||
import { matches } from './search.ts'
|
||||
import ServiceAccountDialog from './ServiceAccountDialog.tsx'
|
||||
import Toolbar from './Toolbar.tsx'
|
||||
import UserDialog from './UserDialog.tsx'
|
||||
@@ -57,40 +58,45 @@ export default function ServiceAccountsPanel() {
|
||||
const [users, setUsers] = useState<string[]>([])
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [unavailable, setUnavailable] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [busy, setBusy] = useState(true)
|
||||
const [adding, setAdding] = useState(false)
|
||||
const [editing, setEditing] = useState<User | null>(null)
|
||||
const [password, setPassword] = useState<string | null>(null)
|
||||
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
|
||||
const [search, setSearch] = useState('')
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const [found, groupList, userList] = await Promise.all([
|
||||
request<ServiceAccounts>('GET', '/service-accounts', SERVICE_ACCOUNTS_SHAPE),
|
||||
request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE),
|
||||
request<{ users: User[] }>('GET', '/users', USERS_SHAPE),
|
||||
])
|
||||
setAccounts(found.service_accounts)
|
||||
setOidc(found.oidc)
|
||||
setGroups(groupList.groups.map((group) => group.name))
|
||||
setUsers(userList.users.map((user) => user.name))
|
||||
setError(null)
|
||||
setUnavailable(false)
|
||||
} catch (caught) {
|
||||
const failure = caught as ApiError
|
||||
setAccounts(null)
|
||||
setUnavailable(failure.status === 404)
|
||||
setError(failure.message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
/** Reads the service accounts with the groups and users; the state changes only once the server answers. */
|
||||
const read = useCallback(async () => {
|
||||
await Promise.all([
|
||||
request<ServiceAccounts>('GET', '/service-accounts', SERVICE_ACCOUNTS_SHAPE),
|
||||
request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE),
|
||||
request<{ users: User[] }>('GET', '/users', USERS_SHAPE),
|
||||
])
|
||||
.then(([found, groupList, userList]) => {
|
||||
setAccounts(found.service_accounts)
|
||||
setOidc(found.oidc)
|
||||
setGroups(groupList.groups.map((group) => group.name))
|
||||
setUsers(userList.users.map((user) => user.name))
|
||||
setError(null)
|
||||
setUnavailable(false)
|
||||
}, (caught) => {
|
||||
const failure = caught as ApiError
|
||||
setAccounts(null)
|
||||
setUnavailable(failure.status === 404)
|
||||
setError(failure.message)
|
||||
})
|
||||
.finally(() => setBusy(false))
|
||||
}, [])
|
||||
|
||||
/** Reads the service accounts again, busy until the server answers. */
|
||||
const refresh = useCallback(() => {
|
||||
setBusy(true)
|
||||
return read()
|
||||
}, [read])
|
||||
|
||||
useEffect(() => {
|
||||
void refresh()
|
||||
}, [refresh])
|
||||
void read()
|
||||
}, [read])
|
||||
|
||||
/** Runs a change of an account, then reads the list again; a failure is shown above the list. */
|
||||
async function change(work: () => Promise<unknown>) {
|
||||
|
||||
@@ -5,8 +5,8 @@ import { DEFAULT_SETTINGS, REFRESH_CHOICES, refreshLabel, saveBrowserSettings, u
|
||||
|
||||
/**
|
||||
* An icon button that opens the settings of this browser: how often the Overview and the Metrics tab read the server on
|
||||
* their own, or manual, when they read only when opened and on Refresh, and whether the shell button opens the shell in
|
||||
* a new tab. A change applies at once and is kept in the browser; Defaults sets every setting back.
|
||||
* their own, or manual, when they read only when opened and on Refresh, and whether the page menu opens the Shell page
|
||||
* in a new tab. A change applies at once and is kept in the browser; Defaults sets every setting back.
|
||||
*/
|
||||
export default function SettingsButton() {
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
+10
-9
@@ -69,16 +69,17 @@ export default function ShellPanel(props: { editorShown: boolean; onFiles: (coun
|
||||
}
|
||||
}, [])
|
||||
|
||||
// The account, then a ticket when its console login is usable.
|
||||
useEffect(() => {
|
||||
request<Account>('GET', '/account', ACCOUNT_SHAPE).then(setAccount).catch((caught: Error) => setError(caught.message))
|
||||
}, [])
|
||||
|
||||
const enabled = login !== null
|
||||
useEffect(() => {
|
||||
if (enabled) {
|
||||
void reopen()
|
||||
}
|
||||
}, [enabled, reopen])
|
||||
request<Account>('GET', '/account', ACCOUNT_SHAPE)
|
||||
.then((found) => {
|
||||
setAccount(found)
|
||||
if (found.console?.enabled && found.otp) {
|
||||
void reopen()
|
||||
}
|
||||
})
|
||||
.catch((caught: Error) => setError(caught.message))
|
||||
}, [reopen])
|
||||
|
||||
useEffect(() => {
|
||||
opened.current = props.onOpened
|
||||
|
||||
+35
-20
@@ -13,7 +13,8 @@ import {
|
||||
} from '@mui/material'
|
||||
import { useCallback, useEffect, useState, type DragEvent, type FormEvent } from 'react'
|
||||
import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
|
||||
import { Section, bytes } from './ServerPanel.tsx'
|
||||
import { Section } from './ServerPanel.tsx'
|
||||
import { bytes } from './format.ts'
|
||||
import Toolbar from './Toolbar.tsx'
|
||||
import {
|
||||
ApiError, SITES_SHAPE, SITE_FILES_SHAPE, SITE_FOLDER_SHAPE, SITE_PATH_SHAPE, download, encodedPath, request, upload,
|
||||
@@ -77,7 +78,7 @@ export default function SiteFiles(props: { site: string | null; onSite: (name: s
|
||||
const [path, setPath] = useState('')
|
||||
const [folder, setFolder] = useState<SiteFolder | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [working, setWorking] = useState(false)
|
||||
const [progress, setProgress] = useState<{ name: string; share: number } | null>(null)
|
||||
const [extract, setExtract] = useState(true)
|
||||
const [creating, setCreating] = useState(false)
|
||||
@@ -91,29 +92,43 @@ export default function SiteFiles(props: { site: string | null; onSite: (name: s
|
||||
request<Sites>('GET', '/sites', SITES_SHAPE).then(setSites).catch((caught) => setError((caught as ApiError).message))
|
||||
}, [])
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (!site) {
|
||||
// The address of the folder shown, null without a site, and the one whose answer is shown.
|
||||
const address = site ? `${base}/${encodedPath(path)}` : null
|
||||
const [shown, setShown] = useState<string | null>(null)
|
||||
const busy = working || (address !== null && shown !== address)
|
||||
|
||||
/** Reads the folder; the state changes only once the server answers. */
|
||||
const read = useCallback(async () => {
|
||||
if (address === null) {
|
||||
return
|
||||
}
|
||||
setBusy(true)
|
||||
try {
|
||||
setFolder(await request<SiteFolder>('GET', `${base}/${encodedPath(path)}`, SITE_FOLDER_SHAPE))
|
||||
setError(null)
|
||||
} catch (caught) {
|
||||
setFolder(null)
|
||||
setError((caught as Error).message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}, [site, base, path])
|
||||
await request<SiteFolder>('GET', address, SITE_FOLDER_SHAPE)
|
||||
.then((found) => {
|
||||
setFolder(found)
|
||||
setError(null)
|
||||
}, (caught) => {
|
||||
setFolder(null)
|
||||
setError((caught as Error).message)
|
||||
})
|
||||
.finally(() => {
|
||||
setShown(address)
|
||||
setWorking(false)
|
||||
})
|
||||
}, [address])
|
||||
|
||||
/** Reads the folder again, busy until the server answers. */
|
||||
const refresh = useCallback(() => {
|
||||
setWorking(true)
|
||||
return read()
|
||||
}, [read])
|
||||
|
||||
useEffect(() => {
|
||||
void refresh()
|
||||
}, [refresh])
|
||||
void read()
|
||||
}, [read])
|
||||
|
||||
/** Runs a change of the files, then reads the folder again; a failure is shown above the list. */
|
||||
async function change(work: () => Promise<unknown>) {
|
||||
setBusy(true)
|
||||
setWorking(true)
|
||||
let failure: string | null = null
|
||||
try {
|
||||
await work()
|
||||
@@ -130,7 +145,7 @@ export default function SiteFiles(props: { site: string | null; onSite: (name: s
|
||||
async function send(files: File[]) {
|
||||
const limit = (sites?.settings.upload_max_mb ?? 0) * 1024 * 1024
|
||||
const failures: string[] = []
|
||||
setBusy(true)
|
||||
setWorking(true)
|
||||
for (const file of files) {
|
||||
if (limit && file.size > limit) {
|
||||
failures.push(`${file.name}: larger than ${sites?.settings.upload_max_mb} MiB.`)
|
||||
@@ -146,7 +161,7 @@ export default function SiteFiles(props: { site: string | null; onSite: (name: s
|
||||
}
|
||||
}
|
||||
setProgress(null)
|
||||
setBusy(false)
|
||||
setWorking(false)
|
||||
await refresh()
|
||||
setError(failures.length ? failures.join('\n') : null)
|
||||
}
|
||||
|
||||
+23
-18
@@ -30,31 +30,36 @@ export default function SiteToSitePanel() {
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [unavailable, setUnavailable] = useState(false)
|
||||
const [note, setNote] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [busy, setBusy] = useState(true)
|
||||
const [adding, setAdding] = useState(false)
|
||||
const [editing, setEditing] = useState<SiteToSiteConnection | null>(null)
|
||||
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const found = await request<{ connections: SiteToSiteConnection[] }>('GET', '/site-to-site', SITE_TO_SITE_SHAPE)
|
||||
setConnections(found.connections)
|
||||
setError(null)
|
||||
setUnavailable(false)
|
||||
} catch (caught) {
|
||||
const failure = caught as ApiError
|
||||
setConnections(null)
|
||||
setUnavailable(failure.status === 404)
|
||||
setError(failure.message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
/** Reads the connections; the state changes only once the server answers. */
|
||||
const read = useCallback(async () => {
|
||||
await request<{ connections: SiteToSiteConnection[] }>('GET', '/site-to-site', SITE_TO_SITE_SHAPE)
|
||||
.then((found) => {
|
||||
setConnections(found.connections)
|
||||
setError(null)
|
||||
setUnavailable(false)
|
||||
}, (caught) => {
|
||||
const failure = caught as ApiError
|
||||
setConnections(null)
|
||||
setUnavailable(failure.status === 404)
|
||||
setError(failure.message)
|
||||
})
|
||||
.finally(() => setBusy(false))
|
||||
}, [])
|
||||
|
||||
/** Reads the connections again, busy until the server answers. */
|
||||
const refresh = useCallback(() => {
|
||||
setBusy(true)
|
||||
return read()
|
||||
}, [read])
|
||||
|
||||
useEffect(() => {
|
||||
void refresh()
|
||||
}, [refresh])
|
||||
void read()
|
||||
}, [read])
|
||||
|
||||
function remove(connection: SiteToSiteConnection) {
|
||||
setConfirm({
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import Refresh from '@mui/icons-material/Refresh'
|
||||
import { Alert, Box, Button } from '@mui/material'
|
||||
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { Grid, IPSEC_HEADS, duration, ipsecRows, text } from './ServerPanel.tsx'
|
||||
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { useBoard } from './useBoard.ts'
|
||||
import { Grid } from './ServerPanel.tsx'
|
||||
import { duration, text } from './format.ts'
|
||||
import { IPSEC_HEADS, ipsecRows } from './ipsec.ts'
|
||||
import Toolbar from './Toolbar.tsx'
|
||||
import { DETAILS_SHAPE, request, type RouterDetails } from './api.ts'
|
||||
import { useRead } from './useRead.ts'
|
||||
|
||||
+36
-29
@@ -9,9 +9,11 @@ import Settings from '@mui/icons-material/Settings'
|
||||
import { Alert, Box, Button, Checkbox, Chip, FormControlLabel, IconButton, Link, Stack, Table, TableBody, TableCell, TableHead, TableRow, Tooltip } from '@mui/material'
|
||||
import { useCallback, useEffect, useState, type ReactNode } from 'react'
|
||||
import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
|
||||
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { useBoard } from './useBoard.ts'
|
||||
import { Copyable, Pairs } from './ServerPanel.tsx'
|
||||
import SearchField, { matches } from './SearchField.tsx'
|
||||
import SearchField from './SearchField.tsx'
|
||||
import { matches } from './search.ts'
|
||||
import SiteDialog, { type SiteSettings } from './SiteDialog.tsx'
|
||||
import SitesSettingsDialog from './SitesSettingsDialog.tsx'
|
||||
import Toolbar from './Toolbar.tsx'
|
||||
@@ -44,7 +46,7 @@ export default function SitesPanel(props: { onOpenFiles: (name: string) => void
|
||||
const [groups, setGroups] = useState<string[]>([])
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [unavailable, setUnavailable] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [busy, setBusy] = useState(true)
|
||||
const [adding, setAdding] = useState(false)
|
||||
const [editing, setEditing] = useState<Site | null>(null)
|
||||
const [settings, setSettings] = useState(false)
|
||||
@@ -52,35 +54,40 @@ export default function SitesPanel(props: { onOpenFiles: (name: string) => void
|
||||
const [search, setSearch] = useState('')
|
||||
const board = useBoard(LAYOUT_KEY)
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const [found, groupList, details] = await Promise.all([
|
||||
request<Sites>('GET', '/sites', SITES_SHAPE),
|
||||
request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE),
|
||||
request<RouterDetails>('GET', '/config', DETAILS_SHAPE),
|
||||
])
|
||||
setSites(found)
|
||||
setGroups(groupList.groups.map((group) => group.name))
|
||||
const wan = details.configuration.wan ?? {}
|
||||
const pki = details.configuration.pki ?? {}
|
||||
setFqdn(typeof wan.local_fqdn === 'string' ? wan.local_fqdn : '')
|
||||
setCas(typeof pki.issuing_cas === 'object' && pki.issuing_cas !== null ? Object.keys(pki.issuing_cas) : [])
|
||||
setError(null)
|
||||
setUnavailable(false)
|
||||
} catch (caught) {
|
||||
const failure = caught as ApiError
|
||||
setSites(null)
|
||||
setUnavailable(failure.status === 404)
|
||||
setError(failure.message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
/** Reads the sites with the groups and the server's details; the state changes only once the server answers. */
|
||||
const read = useCallback(async () => {
|
||||
await Promise.all([
|
||||
request<Sites>('GET', '/sites', SITES_SHAPE),
|
||||
request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE),
|
||||
request<RouterDetails>('GET', '/config', DETAILS_SHAPE),
|
||||
])
|
||||
.then(([found, groupList, details]) => {
|
||||
setSites(found)
|
||||
setGroups(groupList.groups.map((group) => group.name))
|
||||
const wan = details.configuration.wan ?? {}
|
||||
const pki = details.configuration.pki ?? {}
|
||||
setFqdn(typeof wan.local_fqdn === 'string' ? wan.local_fqdn : '')
|
||||
setCas(typeof pki.issuing_cas === 'object' && pki.issuing_cas !== null ? Object.keys(pki.issuing_cas) : [])
|
||||
setError(null)
|
||||
setUnavailable(false)
|
||||
}, (caught) => {
|
||||
const failure = caught as ApiError
|
||||
setSites(null)
|
||||
setUnavailable(failure.status === 404)
|
||||
setError(failure.message)
|
||||
})
|
||||
.finally(() => setBusy(false))
|
||||
}, [])
|
||||
|
||||
/** Reads the sites again, busy until the server answers. */
|
||||
const refresh = useCallback(() => {
|
||||
setBusy(true)
|
||||
return read()
|
||||
}, [read])
|
||||
|
||||
useEffect(() => {
|
||||
void refresh()
|
||||
}, [refresh])
|
||||
void read()
|
||||
}, [read])
|
||||
|
||||
/** Runs a change of a site, then reads the list again; a failure is shown above the list. */
|
||||
async function change(work: () => Promise<unknown>) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Box } from '@mui/material'
|
||||
import ComponentsPanel from './ComponentsPanel.tsx'
|
||||
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
|
||||
import { useBoard } from './useBoard.ts'
|
||||
import Toolbar from './Toolbar.tsx'
|
||||
import UpdatesNotice from './UpdatesNotice.tsx'
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
Alert, Autocomplete, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography,
|
||||
} from '@mui/material'
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import { NAME_PATTERN, NEW_TEMPLATE, daysProblem } from './PkiSettingsDialog.tsx'
|
||||
import { daysProblem, NAME_PATTERN, NEW_TEMPLATE } from './pki.ts'
|
||||
import {
|
||||
BUILTIN_TEMPLATES, KEY_USAGES, OID_PATTERN, PKI_KEYS, SAN_TYPES, TEMPLATE_SUBJECTS, type Pki, type PkiTemplate,
|
||||
} from './api.ts'
|
||||
|
||||
@@ -50,16 +50,13 @@ export default function UpdatesNotice(props: { onBusy?: (busy: boolean) => void;
|
||||
const [rebooting, setRebooting] = useState(false)
|
||||
|
||||
const read = useCallback(async () => {
|
||||
try {
|
||||
const next = await request<UpgradeState>('GET', upgradePath, UPGRADE_SHAPE)
|
||||
await request<UpgradeState>('GET', upgradePath, UPGRADE_SHAPE).then((next) => {
|
||||
setUpgrade(next)
|
||||
setUnreachable(false)
|
||||
if (next.state !== 'running') {
|
||||
request<Updates>('GET', updatesPath, UPDATES_SHAPE).then(setUpdates, (caught: Error) => setError(caught.message))
|
||||
}
|
||||
} catch {
|
||||
setUnreachable(true)
|
||||
}
|
||||
}, () => setUnreachable(true))
|
||||
}, [updatesPath, upgradePath])
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
+25
-18
@@ -20,7 +20,8 @@ import OtpDialog from './OtpDialog.tsx'
|
||||
import PersonDialog from './PersonDialog.tsx'
|
||||
import ProfileDialog from './ProfileDialog.tsx'
|
||||
import { Section } from './ServerPanel.tsx'
|
||||
import SearchField, { matches } from './SearchField.tsx'
|
||||
import SearchField from './SearchField.tsx'
|
||||
import { matches } from './search.ts'
|
||||
import Toolbar from './Toolbar.tsx'
|
||||
import UserDialog from './UserDialog.tsx'
|
||||
import {
|
||||
@@ -54,7 +55,7 @@ export default function UsersPanel() {
|
||||
const [users, setUsers] = useState<User[] | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [unavailable, setUnavailable] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [busy, setBusy] = useState(true)
|
||||
const [adding, setAdding] = useState(false)
|
||||
const [password, setPassword] = useState<string | null>(null)
|
||||
const [details, setDetails] = useState<User | null>(null)
|
||||
@@ -66,8 +67,8 @@ export default function UsersPanel() {
|
||||
const [search, setSearch] = useState('')
|
||||
const [kind, setKind] = useState<Kind>('all')
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setBusy(true)
|
||||
/** Reads the users; the state changes only once the server answers. */
|
||||
const read = useCallback(async () => {
|
||||
// The status has openvpn and p2s while the server runs OpenVPN and IKEv2, which the profiles need; null while it is
|
||||
// not known.
|
||||
request<RouterStatus>('GET', '/status/full', STATUS_SHAPE)
|
||||
@@ -79,23 +80,29 @@ export default function UsersPanel() {
|
||||
setOpenvpn(null)
|
||||
setP2s(null)
|
||||
})
|
||||
try {
|
||||
setUsers((await request<{ users: User[] }>('GET', '/users', USERS_SHAPE)).users)
|
||||
setError(null)
|
||||
setUnavailable(false)
|
||||
} catch (caught) {
|
||||
const failure = caught as ApiError
|
||||
setUsers(null)
|
||||
setUnavailable(failure.status === 404)
|
||||
setError(failure.message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
await request<{ users: User[] }>('GET', '/users', USERS_SHAPE)
|
||||
.then((found) => {
|
||||
setUsers(found.users)
|
||||
setError(null)
|
||||
setUnavailable(false)
|
||||
}, (caught) => {
|
||||
const failure = caught as ApiError
|
||||
setUsers(null)
|
||||
setUnavailable(failure.status === 404)
|
||||
setError(failure.message)
|
||||
})
|
||||
.finally(() => setBusy(false))
|
||||
}, [])
|
||||
|
||||
/** Reads the users again, busy until the server answers. */
|
||||
const refresh = useCallback(() => {
|
||||
setBusy(true)
|
||||
return read()
|
||||
}, [read])
|
||||
|
||||
useEffect(() => {
|
||||
void refresh()
|
||||
}, [refresh])
|
||||
void read()
|
||||
}, [read])
|
||||
|
||||
/** Runs a change of a user, then reads the list again; a failure is shown above the list after the reading. */
|
||||
async function change(work: () => Promise<unknown>) {
|
||||
|
||||
@@ -14,7 +14,8 @@ const PREFILLED_LINES = 2
|
||||
* device's address, its peer's IPs, or a placeholder without them (ips null). The device's private key is a
|
||||
* placeholder, which the server never has; a switch leaves out the [Interface] and PrivateKey lines, which a client such
|
||||
* as WireGuard for Windows fills in for a new empty tunnel, and keeps its position in the browser's settings. Copy
|
||||
* puts the configuration as shown on the clipboard.
|
||||
* puts the configuration as shown on the clipboard; it is shown only on a page served over HTTPS, where the browser
|
||||
* offers the clipboard.
|
||||
*/
|
||||
export default function WireGuardConfigDialog(props: { title: string; server: WireGuardServer; ips: string[] | null; onClose: () => void }) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
@@ -43,9 +44,11 @@ export default function WireGuardConfigDialog(props: { title: string; server: Wi
|
||||
</Box>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button startIcon={copied ? <Check /> : <ContentCopy />} onClick={() => void navigator.clipboard.writeText(text).then(() => setCopied(true))}>
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
</Button>
|
||||
{window.isSecureContext && (
|
||||
<Button startIcon={copied ? <Check /> : <ContentCopy />} onClick={() => void navigator.clipboard.writeText(text).then(() => setCopied(true))}>
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="contained" onClick={props.onClose}>Close</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
+10
-9
@@ -91,6 +91,10 @@ export type RouterDetails = {
|
||||
external_addresses?: string[]
|
||||
internal_address?: string
|
||||
internal_gateway?: string
|
||||
/** The names HTTPS is served for: wan.local_fqdn, or the host name and <host name>.local without it. */
|
||||
https_names?: string[]
|
||||
/** The addresses HTTPS is served for while https.ip_sans is on. */
|
||||
https_addresses?: string[]
|
||||
local_cidrs?: string[]
|
||||
/** Each site-to-site connection with the identities and subnets the server resolved for it. */
|
||||
site_to_site?: { name: string; local_identity: string; remote_identity: string; local_cidrs: string[]; remote_cidrs: string[] }[]
|
||||
@@ -346,9 +350,6 @@ export type Backup = {
|
||||
/** The key types of the CAs and of the templates. */
|
||||
export const PKI_KEYS = ['rsa-2048', 'rsa-3072', 'rsa-4096', 'ec-p256', 'ec-p384'] as const
|
||||
|
||||
/** Where the CA certificates and CRLs are published, in the order the certificates list the URLs. */
|
||||
export const PKI_PUBLISH = ['http', 'http-80', 'https', 'https-default'] as const
|
||||
|
||||
/** The key usages a template may give. */
|
||||
export const KEY_USAGES = ['digital_signature', 'content_commitment', 'key_encipherment', 'data_encipherment', 'key_agreement'] as const
|
||||
|
||||
@@ -391,7 +392,6 @@ export type PkiSettings = {
|
||||
key: string
|
||||
crl_days: number
|
||||
root_crl_days: number
|
||||
publish: string[]
|
||||
p2s_name: string
|
||||
s2s_name: string
|
||||
servers_name: string
|
||||
@@ -506,10 +506,10 @@ export type AcmeProvider = (typeof ACME_PROVIDERS)[number]
|
||||
* the certificate source, '' until the first setup chooses it, and the ACME settings.
|
||||
*/
|
||||
export type HttpsSettings = {
|
||||
enabled: boolean
|
||||
email: string
|
||||
web_port: number
|
||||
manager_port: number
|
||||
ip_sans: boolean
|
||||
acme_staging: boolean
|
||||
certificate: HttpsCertificateSource | ''
|
||||
self_signed_days: number
|
||||
@@ -521,8 +521,8 @@ export type HttpsSettings = {
|
||||
}
|
||||
|
||||
/** The changes PUT /https/settings takes; a secret left out keeps its value. */
|
||||
export type HttpsChange = Partial<Pick<HttpsSettings, 'acme_staging' | 'certificate' | 'self_signed_days' | 'acme_provider' |
|
||||
'acme_url' | 'acme_eab_key_id'>> & { acme_eab_mac_key?: string; zerossl_api_key?: string }
|
||||
export type HttpsChange = Partial<Pick<HttpsSettings, 'acme_staging' | 'certificate' | 'self_signed_days' | 'ip_sans' |
|
||||
'acme_provider' | 'acme_url' | 'acme_eab_key_id'>> & { acme_eab_mac_key?: string; zerossl_api_key?: string }
|
||||
|
||||
/**
|
||||
* The server's HTTPS certificate: the chosen source, '' until the first setup chooses it, the one served (self-signed while the chosen one is not
|
||||
@@ -704,6 +704,8 @@ export const DETAILS_SHAPE = object({
|
||||
external_addresses: optional(list(string)),
|
||||
internal_address: optional(string),
|
||||
internal_gateway: optional(string),
|
||||
https_names: optional(list(string)),
|
||||
https_addresses: optional(list(string)),
|
||||
local_cidrs: optional(list(string)),
|
||||
site_to_site: optional(list(object({
|
||||
name: string,
|
||||
@@ -977,7 +979,6 @@ const PKI_SETTINGS: Check = object({
|
||||
key: string,
|
||||
crl_days: number,
|
||||
root_crl_days: number,
|
||||
publish: list(string),
|
||||
p2s_name: string,
|
||||
s2s_name: string,
|
||||
servers_name: string,
|
||||
@@ -1159,10 +1160,10 @@ export const METRICS_SETTINGS_SHAPE = object({
|
||||
/** The shape of GET and PUT /https/settings; GET also has the certificate. */
|
||||
export const HTTPS_SETTINGS_SHAPE = object({
|
||||
settings: object({
|
||||
enabled: boolean,
|
||||
email: string,
|
||||
web_port: number,
|
||||
manager_port: number,
|
||||
ip_sans: boolean,
|
||||
acme_staging: boolean,
|
||||
certificate: string,
|
||||
self_signed_days: number,
|
||||
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user