Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d6aea8390f | ||
|
|
5981b2be32 | ||
|
|
2af64d8868 | ||
|
|
108dac0748 | ||
|
|
3fa32335cc | ||
|
|
8295c185ed | ||
|
|
4e32e842b0 | ||
|
|
41ecc592d1 | ||
|
|
d4e361b5ba | ||
|
|
64474185fb | ||
|
|
7a7a4cc44f | ||
|
|
98616431e7 | ||
|
|
b24a57733f
|
No files matched your search
@@ -0,0 +1,74 @@
|
||||
# CodeQL on every pull request, contributors' forks included, on every push
|
||||
# to main, and once a week (new queries find old code).
|
||||
#
|
||||
# GitHub's default setup for code scanning skips pull requests from forks, so
|
||||
# a contributor's change was first scanned after it was merged. This replaces
|
||||
# it: turn default setup off (Settings > Code security > CodeQL analysis) when
|
||||
# this lands, as GitHub refuses results from a workflow while it is on.
|
||||
#
|
||||
# Safe for pull requests from forks: it uses pull_request (never
|
||||
# pull_request_target), so a fork's code runs with a read-only token and no
|
||||
# secrets, and nothing is built (build-mode: none), so no fork code executes.
|
||||
# If GitHub refuses a fork's upload, the analyze step fails: a pull request is
|
||||
# never shown as scanned when it wasn't. The alerts are in the run's summary
|
||||
# either way.
|
||||
name: CodeQL
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
schedule:
|
||||
- cron: "27 4 * * 1"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: codeql-${{ github.event.pull_request.number || github.ref }}-${{ github.event_name }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze (${{ matrix.language }})
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 60
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
security-events: write
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: [actions, javascript-typescript, python, rust]
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: none
|
||||
queries: security-extended
|
||||
- uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
|
||||
with:
|
||||
category: /language:${{ matrix.language }}
|
||||
output: sarif
|
||||
- name: List the alerts in the summary
|
||||
if: always()
|
||||
run: |
|
||||
ls sarif/*.sarif >/dev/null 2>&1 || { echo "No CodeQL results: the analysis did not finish." >> "$GITHUB_STEP_SUMMARY"; exit 0; }
|
||||
python3 - sarif/*.sarif >> "$GITHUB_STEP_SUMMARY" <<'EOF'
|
||||
import json, sys
|
||||
rows = []
|
||||
for path in sys.argv[1:]:
|
||||
for run in json.load(open(path))["runs"]:
|
||||
for r in run["results"]:
|
||||
loc = r["locations"][0]["physicalLocation"]
|
||||
text = r["message"]["text"].splitlines()[0].replace("|", "\\|")
|
||||
rows.append(f"| `{r['ruleId']}` | `{loc['artifactLocation']['uri']}:{loc['region'].get('startLine', '')}` | {text} |")
|
||||
print(f"### CodeQL ({len(rows)} alerts, before dismissals)\n")
|
||||
if rows:
|
||||
print("| Rule | Where | What |\n|---|---|---|")
|
||||
print("\n".join(rows))
|
||||
EOF
|
||||
@@ -0,0 +1,35 @@
|
||||
# The window's page tests (scripts/ui-test.py) on every pull request, so a
|
||||
# change that breaks one shows on the PR before review.
|
||||
#
|
||||
# Safe for pull requests from forks: it runs on GitHub's machines with a
|
||||
# read-only token and no secrets, and uses pull_request (never
|
||||
# pull_request_target), so a fork's code can't write to the repository.
|
||||
name: UI tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ui-tests-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
ui:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Run the page tests in headless Chrome
|
||||
run: |
|
||||
# The runner's Chrome, without the sandbox: it needs user
|
||||
# namespaces the runner doesn't allow.
|
||||
printf '#!/bin/sh\nexec google-chrome --no-sandbox "$@"\n' > "$RUNNER_TEMP/chrome"
|
||||
chmod +x "$RUNNER_TEMP/chrome"
|
||||
CHROME="$RUNNER_TEMP/chrome" python3 scripts/ui-test.py
|
||||
+2
-1
@@ -33,7 +33,8 @@ once; see the README.
|
||||
- `python3 scripts/ui-test.py` must pass. Its parity test opens the window as
|
||||
each system and fails when one shows something another doesn't, unless
|
||||
`tests/ui/parity-allow.txt` gives the reason. A new line there needs a
|
||||
maintainer's OK.
|
||||
maintainer's OK. It also runs on every pull request; on Linux, point
|
||||
`CHROME` at your Chrome or Chromium.
|
||||
|
||||
## Pull requests
|
||||
|
||||
|
||||
@@ -80,8 +80,23 @@ impl Image {
|
||||
}
|
||||
|
||||
/// `repo@digest` as Docker shows it, by the index's digest if there was one.
|
||||
pub fn repo_digest(&self) -> String {
|
||||
format!("{}@{}", self.repo(), self.index_digest.as_deref().unwrap_or(&self.digest))
|
||||
/// None for an image no registry has yet (built, loaded, committed, tagged
|
||||
/// for another repository): its digest is its config's, which a manifest's
|
||||
/// can never be, as the manifest holds it.
|
||||
pub fn repo_digest(&self) -> Option<String> {
|
||||
let d = self.index_digest.as_deref().unwrap_or(&self.digest);
|
||||
(d != self.config_digest).then(|| format!("{}@{d}", self.repo()))
|
||||
}
|
||||
|
||||
/// This image under another name (`docker tag`). Its registry digests
|
||||
/// belong to its repository: in another one it has none until a push.
|
||||
pub fn tagged(&self, name: String) -> Image {
|
||||
let mut i = Image { name, ..self.clone() };
|
||||
if i.repo() != self.repo() {
|
||||
i.digest = self.config_digest.clone();
|
||||
i.index_digest = None;
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
/// True if `r` names this image: its name, or a digest of its repository
|
||||
@@ -202,6 +217,20 @@ impl Store {
|
||||
self.write_index(&images)
|
||||
}
|
||||
|
||||
/// Records the manifest a push of `name` left in its registry, so
|
||||
/// RepoDigests names what the registry has, as Docker's does: deploy tools
|
||||
/// pin to it. Every tag of the image in that repository gets it, as there.
|
||||
/// Not if `name` became another image during the push.
|
||||
pub fn set_pushed(&self, name: &str, config_digest: &str, digest: &str) -> io::Result<()> {
|
||||
let mut images = self.images()?;
|
||||
let Some(repo) = images.iter().find(|i| i.name == name && i.config_digest == config_digest).map(|i| i.repo().to_owned()) else { return Ok(()) };
|
||||
for i in images.iter_mut().filter(|i| i.config_digest == config_digest && i.repo() == repo) {
|
||||
i.digest = digest.to_owned();
|
||||
i.index_digest = None;
|
||||
}
|
||||
self.write_index(&images)
|
||||
}
|
||||
|
||||
/// Removes the image and deletes blobs no remaining image uses.
|
||||
pub fn remove_image(&self, name: &str) -> io::Result<Option<Image>> {
|
||||
let mut images = self.images()?;
|
||||
@@ -384,7 +413,7 @@ mod tests {
|
||||
config: RunConfig::default(),
|
||||
};
|
||||
assert_eq!(image.repo(), "kindest/node");
|
||||
assert_eq!(image.repo_digest(), format!("kindest/node@{index}"));
|
||||
assert_eq!(image.repo_digest(), Some(format!("kindest/node@{index}")));
|
||||
store.put_image(image).unwrap();
|
||||
for name in [format!("kindest/node@{index}"), format!("kindest/node:v1.37.0@{index}"), format!("kindest/node@{manifest}"), manifest.clone()] {
|
||||
assert!(store.find(&name).unwrap().is_some(), "{name}");
|
||||
@@ -393,6 +422,53 @@ mod tests {
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_push_leaves_the_registry_manifest_in_repo_digests() {
|
||||
let root = std::env::temp_dir().join(format!("kiri-store-push-test-{}", std::process::id()));
|
||||
let store = Store::open(&root).unwrap();
|
||||
let d = |c: &str| format!("sha256:{}", c.repeat(64));
|
||||
let image = |name: &str, config: &str, index: Option<String>| Image {
|
||||
name: name.into(),
|
||||
digest: d(config),
|
||||
index_digest: index,
|
||||
config_digest: d(config),
|
||||
layers: Vec::new(),
|
||||
size: 0,
|
||||
platform: "linux/arm64".into(),
|
||||
created: String::new(),
|
||||
pulled_at: 0,
|
||||
config: RunConfig::default(),
|
||||
};
|
||||
// Built here: no registry has it yet, so no RepoDigest, as with Docker.
|
||||
store.put_image(image("localhost:5000/built:1", "1", None)).unwrap();
|
||||
// The same image's other tags: one in its repository, one in another registry.
|
||||
store.put_image(image("localhost:5000/built:latest", "1", None)).unwrap();
|
||||
store.put_image(image("localhost:5001/built:1", "1", None)).unwrap();
|
||||
// Pulled: alpine's index. Tagged in its repository it keeps that; in
|
||||
// another it has none there, rather than a digest that one lacks.
|
||||
let pulled = Image { digest: d("8"), ..image("alpine:latest", "2", Some(d("9"))) };
|
||||
assert_eq!(pulled.tagged("alpine:old".into()).repo_digest(), Some(format!("alpine@{}", d("9"))));
|
||||
store.put_image(pulled.tagged("localhost:5000/tagged:1".into())).unwrap();
|
||||
store.put_image(image("localhost:5000/other:1", "3", None)).unwrap();
|
||||
let repo_digest = |n: &str| store.find(n).unwrap().unwrap().repo_digest();
|
||||
for n in ["localhost:5000/built:1", "localhost:5000/tagged:1", "localhost:5000/other:1"] {
|
||||
assert_eq!(repo_digest(n), None, "{n}");
|
||||
}
|
||||
store.set_pushed("localhost:5000/built:1", &d("1"), &d("a")).unwrap();
|
||||
store.set_pushed("localhost:5000/tagged:1", &d("2"), &d("b")).unwrap();
|
||||
// The name now another image: that one keeps its own.
|
||||
store.set_pushed("localhost:5000/other:1", &d("4"), &d("c")).unwrap();
|
||||
assert_eq!(repo_digest("localhost:5000/built:1"), Some(format!("localhost:5000/built@{}", d("a"))));
|
||||
// Pushing one tag gives the repository's other tags of it the digest; elsewhere it has none.
|
||||
assert_eq!(repo_digest("localhost:5000/built:latest"), Some(format!("localhost:5000/built@{}", d("a"))));
|
||||
assert_eq!(repo_digest("localhost:5001/built:1"), None);
|
||||
assert_eq!(repo_digest("localhost:5000/tagged:1"), Some(format!("localhost:5000/tagged@{}", d("b"))));
|
||||
assert_eq!(repo_digest("localhost:5000/other:1"), None);
|
||||
// And a pull by the pushed digest finds the image here.
|
||||
assert!(store.find(&format!("localhost:5000/built@{}", d("a"))).unwrap().is_some());
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repo_strips_a_tag_but_not_a_port() {
|
||||
let named = |name: &str| Image {
|
||||
|
||||
@@ -9,52 +9,372 @@
|
||||
//!
|
||||
//! The daemon writes the list when it makes the socket, and `kiri host-access`
|
||||
//! (run as root, from the window's onboarding through pkexec) writes it again
|
||||
//! after adding someone. Someone taken out of the group keeps their entry
|
||||
//! until the engine restarts and the socket is made again.
|
||||
//! after adding someone.
|
||||
//!
|
||||
//! An entry in the list outlives the membership it was written for, so the
|
||||
//! daemon doesn't rely on it alone: a `Gate` checks every new connection
|
||||
//! against the group, and every few seconds checks the people still connected,
|
||||
//! closing the connections of anyone removed (streams and `exec` sessions
|
||||
//! too) and writing the list again without them. Removal applies as soon as
|
||||
//! the system's user database says so; where that is cached (nscd, sssd), it
|
||||
//! is when the cache catches up.
|
||||
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ffi::{CStr, CString, OsStr};
|
||||
use std::io;
|
||||
use std::net::Shutdown;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::raw::{c_char, c_int};
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How often the people still connected are checked again.
|
||||
const RECHECK: Duration = Duration::from_secs(2);
|
||||
|
||||
/// An account or group record and the buffer its strings live in.
|
||||
struct Rec<T> {
|
||||
rec: T,
|
||||
_buf: Vec<c_char>,
|
||||
}
|
||||
|
||||
/// Runs a reentrant NSS lookup (getpwuid_r and the like), growing the buffer
|
||||
/// until the record fits. `Ok(None)`: there is no such account or group.
|
||||
///
|
||||
/// # Safety
|
||||
/// `T` must be `libc::passwd` or `libc::group`, and `call` the matching `_r` lookup.
|
||||
unsafe fn nss<T>(mut call: impl FnMut(*mut T, *mut c_char, usize, *mut *mut T) -> c_int) -> io::Result<Option<Rec<T>>> {
|
||||
let mut size = 1024;
|
||||
loop {
|
||||
let mut buf: Vec<c_char> = vec![0; size];
|
||||
// SAFETY: passwd and group are plain data; all-zero is a valid value.
|
||||
let mut rec: T = unsafe { std::mem::zeroed() };
|
||||
let mut out: *mut T = std::ptr::null_mut();
|
||||
match call(&mut rec, buf.as_mut_ptr(), buf.len(), &mut out) {
|
||||
0 if out.is_null() => return Ok(None),
|
||||
// The record's strings point into `buf`, whose heap storage moves with it.
|
||||
0 => return Ok(Some(Rec { rec, _buf: buf })),
|
||||
// Groups of many thousands of names run to megabytes.
|
||||
libc::ERANGE if size < 1 << 28 => size *= 2,
|
||||
libc::ENOENT | libc::ESRCH => return Ok(None),
|
||||
e => return Err(io::Error::from_raw_os_error(e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn account_by_uid(uid: u32) -> io::Result<Option<Rec<libc::passwd>>> {
|
||||
// SAFETY: getpwuid_r with a passwd record and a buffer of the stated size.
|
||||
unsafe { nss(|rec, buf, len, out| libc::getpwuid_r(uid, rec, buf, len, out)) }
|
||||
}
|
||||
|
||||
fn account_by_name(name: &CStr) -> io::Result<Option<Rec<libc::passwd>>> {
|
||||
// SAFETY: getpwnam_r with a valid C string, a passwd record and a buffer of the stated size.
|
||||
unsafe { nss(|rec, buf, len, out| libc::getpwnam_r(name.as_ptr(), rec, buf, len, out)) }
|
||||
}
|
||||
|
||||
fn group_by_name(name: &CStr) -> io::Result<Rec<libc::group>> {
|
||||
// SAFETY: getgrnam_r with a valid C string, a group record and a buffer of the stated size.
|
||||
unsafe { nss(|rec, buf, len, out| libc::getgrnam_r(name.as_ptr(), rec, buf, len, out)) }?
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, format!("no group {}", name.to_string_lossy())))
|
||||
}
|
||||
|
||||
fn c_name(s: &str) -> io::Result<CString> {
|
||||
CString::new(s).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))
|
||||
}
|
||||
|
||||
/// The account names listed in a group record.
|
||||
fn names(group: &libc::group) -> Vec<&CStr> {
|
||||
let mut out = Vec::new();
|
||||
let mut m = group.gr_mem;
|
||||
// SAFETY: gr_mem is a NULL-terminated array of account names for this group.
|
||||
unsafe {
|
||||
while !m.is_null() && !(*m).is_null() {
|
||||
out.push(CStr::from_ptr(*m));
|
||||
m = m.add(1);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn group_members(group: &CStr) -> io::Result<Vec<String>> {
|
||||
let g = group_by_name(group)?;
|
||||
Ok(names(&g.rec).iter().map(|n| n.to_string_lossy().into_owned()).collect())
|
||||
}
|
||||
|
||||
/// The users in `group` by name (its member list, not primary-group users).
|
||||
pub fn members(group: &str) -> io::Result<Vec<String>> {
|
||||
let name = CString::new(group).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?;
|
||||
// SAFETY: getgrnam with a valid C string; its result is copied out at once,
|
||||
// before anything else could reuse its static storage.
|
||||
unsafe {
|
||||
let g = libc::getgrnam(name.as_ptr());
|
||||
if g.is_null() {
|
||||
return Err(io::Error::new(io::ErrorKind::NotFound, format!("no group {group}")));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut m = (*g).gr_mem;
|
||||
while !m.is_null() && !(*m).is_null() {
|
||||
out.push(CStr::from_ptr(*m).to_string_lossy().into_owned());
|
||||
m = m.add(1);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
group_members(&c_name(group)?)
|
||||
}
|
||||
|
||||
/// A user's numeric id, if the account exists.
|
||||
pub fn uid(user: &str) -> Option<u32> {
|
||||
let name = CString::new(user).ok()?;
|
||||
// SAFETY: getpwnam with a valid C string; the uid is read at once.
|
||||
unsafe {
|
||||
let p = libc::getpwnam(name.as_ptr());
|
||||
(!p.is_null()).then(|| (*p).pw_uid)
|
||||
let a = account_by_name(&c_name(user).ok()?).ok()??;
|
||||
Some(a.rec.pw_uid)
|
||||
}
|
||||
|
||||
/// The uids of the names in a group record, sorted. A name with no account
|
||||
/// is left out; a lookup that fails fails the whole list, so a slow directory
|
||||
/// never shrinks it.
|
||||
fn uids_of(group: &libc::group) -> io::Result<Vec<u32>> {
|
||||
let mut out = Vec::new();
|
||||
for name in names(group) {
|
||||
if let Some(a) = account_by_name(name)? {
|
||||
out.push(a.rec.pw_uid);
|
||||
}
|
||||
}
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn member_uids(group: &CStr) -> io::Result<Vec<u32>> {
|
||||
uids_of(&group_by_name(group)?.rec)
|
||||
}
|
||||
|
||||
/// Gives every member of `group` read-write access to `socket` by name, so a
|
||||
/// member just added can use it without signing in again. Returns how many.
|
||||
pub fn grant(socket: &Path, group: &str) -> io::Result<usize> {
|
||||
let uids: Vec<u32> = members(group)?.iter().filter_map(|u| uid(u)).collect();
|
||||
let uids = member_uids(&c_name(group)?)?;
|
||||
set(socket, &uids)?;
|
||||
Ok(uids.len())
|
||||
}
|
||||
|
||||
/// The uid at the other end of an accepted connection.
|
||||
fn peer_uid(conn: &UnixStream) -> io::Result<u32> {
|
||||
// SAFETY: a connected socket and zeroed storage for its credentials.
|
||||
let mut cred: libc::ucred = unsafe { std::mem::zeroed() };
|
||||
let mut len = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
|
||||
// SAFETY: the output pointers are valid and the buffer is the stated size.
|
||||
let r = unsafe { libc::getsockopt(conn.as_raw_fd(), libc::SOL_SOCKET, libc::SO_PEERCRED, (&mut cred as *mut libc::ucred).cast(), &mut len) };
|
||||
if r != 0 || len as usize != std::mem::size_of::<libc::ucred>() {
|
||||
return Err(if r != 0 { io::Error::last_os_error() } else { io::Error::new(io::ErrorKind::InvalidData, "short peer credentials") });
|
||||
}
|
||||
Ok(cred.uid)
|
||||
}
|
||||
|
||||
/// Whether the account is in the group by name or as its primary group.
|
||||
fn group_member(user: &CStr, primary_gid: libc::gid_t, group: &libc::group) -> bool {
|
||||
primary_gid == group.gr_gid || names(group).contains(&user)
|
||||
}
|
||||
|
||||
/// The group's record, or `None` if the group was deleted: that leaves
|
||||
/// nobody in it, which is an answer, not a failure.
|
||||
fn current(group: &CStr) -> io::Result<Option<Rec<libc::group>>> {
|
||||
match group_by_name(group) {
|
||||
Ok(g) => Ok(Some(g)),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the account `uid` is in the group now. No account, or no group: no.
|
||||
fn member_of(uid: u32, group: Option<&libc::group>) -> io::Result<bool> {
|
||||
let Some(group) = group else { return Ok(false) };
|
||||
let Some(a) = account_by_uid(uid)? else { return Ok(false) };
|
||||
if a.rec.pw_name.is_null() {
|
||||
return Ok(false);
|
||||
}
|
||||
// SAFETY: pw_name is a NUL-terminated string in the record's buffer.
|
||||
let user = unsafe { CStr::from_ptr(a.rec.pw_name) };
|
||||
Ok(group_member(user, a.rec.pw_gid, group))
|
||||
}
|
||||
|
||||
fn member(uid: u32, group: &CStr) -> io::Result<bool> {
|
||||
member_of(uid, current(group)?.as_ref().map(|g| &g.rec))
|
||||
}
|
||||
|
||||
/// Who may use the engine's socket: root, the account the daemon runs as, and
|
||||
/// the members of one group, checked when they connect and again while they
|
||||
/// stay connected.
|
||||
pub struct Gate {
|
||||
group: CString,
|
||||
socket: PathBuf,
|
||||
owner: u32,
|
||||
open: Mutex<HashMap<u64, (u32, UnixStream)>>,
|
||||
next: AtomicU64,
|
||||
failing: AtomicBool,
|
||||
/// Recent answers by uid, so the docker CLI's burst of connections per
|
||||
/// command costs one lookup. They last no longer than the recheck does.
|
||||
recent: Mutex<HashMap<u32, (bool, Instant)>>,
|
||||
}
|
||||
|
||||
/// A connection the gate let in; dropping it stops watching that connection.
|
||||
pub struct Seat {
|
||||
gate: Arc<Gate>,
|
||||
id: u64,
|
||||
}
|
||||
|
||||
impl Drop for Seat {
|
||||
fn drop(&mut self) {
|
||||
self.gate.open.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.id);
|
||||
}
|
||||
}
|
||||
|
||||
impl Gate {
|
||||
pub fn new(socket: &Path, group: &OsStr) -> io::Result<Arc<Gate>> {
|
||||
let group = CString::new(group.as_bytes()).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?;
|
||||
// SAFETY: geteuid cannot fail.
|
||||
let owner = unsafe { libc::geteuid() };
|
||||
Ok(Arc::new(Gate { group, socket: socket.to_owned(), owner, open: Mutex::default(), next: AtomicU64::new(0), failing: AtomicBool::new(false), recent: Mutex::default() }))
|
||||
}
|
||||
|
||||
fn name(&self) -> std::borrow::Cow<'_, str> {
|
||||
self.group.to_string_lossy()
|
||||
}
|
||||
|
||||
fn allowed(&self, uid: u32) -> io::Result<bool> {
|
||||
if uid == 0 || uid == self.owner {
|
||||
return Ok(true);
|
||||
}
|
||||
if let Some((yes, at)) = self.recent.lock().unwrap_or_else(|e| e.into_inner()).get(&uid)
|
||||
&& at.elapsed() < RECHECK
|
||||
{
|
||||
return Ok(*yes);
|
||||
}
|
||||
let yes = member(uid, &self.group)?;
|
||||
self.remember(uid, yes);
|
||||
Ok(yes)
|
||||
}
|
||||
|
||||
fn remember(&self, uid: u32, yes: bool) {
|
||||
let mut recent = self.recent.lock().unwrap_or_else(|e| e.into_inner());
|
||||
recent.retain(|_, (_, at)| at.elapsed() < RECHECK);
|
||||
recent.insert(uid, (yes, Instant::now()));
|
||||
}
|
||||
|
||||
/// One recheck: everyone connected against one read of the group, then
|
||||
/// the access list, if the group's names changed since it was written.
|
||||
/// `listed`: the names the list was last written for.
|
||||
fn tick(&self, listed: &mut Option<Vec<CString>>) {
|
||||
let group = current(&self.group);
|
||||
let connected = !self.open.lock().unwrap_or_else(|e| e.into_inner()).is_empty();
|
||||
if connected {
|
||||
self.sweep_with(|uid| {
|
||||
if uid == 0 || uid == self.owner {
|
||||
return Ok(true);
|
||||
}
|
||||
let g = group.as_ref().map_err(|e| io::Error::new(e.kind(), e.to_string()))?;
|
||||
let yes = member_of(uid, g.as_ref().map(|g| &g.rec))?;
|
||||
self.remember(uid, yes);
|
||||
Ok(yes)
|
||||
});
|
||||
}
|
||||
let Ok(group) = group else { return };
|
||||
let now: Vec<CString> = group.as_ref().map(|g| names(&g.rec).into_iter().map(CStr::to_owned).collect()).unwrap_or_default();
|
||||
if listed.as_ref() == Some(&now) {
|
||||
return;
|
||||
}
|
||||
// Only a list actually written counts: anything else is tried again.
|
||||
let written = group.as_ref().map_or(Ok(Vec::new()), |g| uids_of(&g.rec)).and_then(|uids| set(&self.socket, &uids).map(|()| uids.len()));
|
||||
match written {
|
||||
Ok(n) => {
|
||||
crate::diag::info!("socket access list written", members = n);
|
||||
*listed = Some(now);
|
||||
}
|
||||
Err(e) if unsupported(&e) => *listed = Some(now),
|
||||
Err(e) => crate::diag::warn!("socket access list not written", error = e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the socket's access list for the group's current members.
|
||||
pub fn grant(&self) -> io::Result<usize> {
|
||||
let uids = member_uids(&self.group)?;
|
||||
set(&self.socket, &uids)?;
|
||||
Ok(uids.len())
|
||||
}
|
||||
|
||||
/// Checks a new connection. `None`: refused, and the reason logged.
|
||||
pub fn admit(self: &Arc<Self>, conn: &UnixStream) -> Option<Seat> {
|
||||
self.admit_with(conn, |uid| self.allowed(uid))
|
||||
}
|
||||
|
||||
fn admit_with(self: &Arc<Self>, conn: &UnixStream, check: impl Fn(u32) -> io::Result<bool>) -> Option<Seat> {
|
||||
let checked = peer_uid(conn).and_then(|uid| Ok((uid, check(uid)?)));
|
||||
let uid = match checked {
|
||||
Ok((uid, true)) => uid,
|
||||
Ok((uid, false)) => {
|
||||
crate::diag::warn!("socket connection refused: user is not in the access group", group = self.name(), uid = uid);
|
||||
return None;
|
||||
}
|
||||
Err(e) => {
|
||||
crate::diag::warn!("socket connection refused: access check failed", group = self.name(), error = e);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let keep = match conn.try_clone() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
crate::diag::warn!("socket connection refused: cannot watch it", error = e);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let id = self.next.fetch_add(1, Ordering::Relaxed);
|
||||
self.open.lock().unwrap_or_else(|e| e.into_inner()).insert(id, (uid, keep));
|
||||
Some(Seat { gate: self.clone(), id })
|
||||
}
|
||||
|
||||
/// Checks everyone still connected, once per account, and closes the
|
||||
/// connections of anyone no longer allowed. A failed lookup leaves the
|
||||
/// connections open (new ones are refused until lookups work again).
|
||||
fn sweep_with(&self, check: impl Fn(u32) -> io::Result<bool>) -> usize {
|
||||
let uids: HashSet<u32> = self.open.lock().unwrap_or_else(|e| e.into_inner()).values().map(|(u, _)| *u).collect();
|
||||
let mut removed = HashSet::new();
|
||||
let mut failed = None;
|
||||
for uid in uids {
|
||||
match check(uid) {
|
||||
Ok(true) => {}
|
||||
Ok(false) => {
|
||||
removed.insert(uid);
|
||||
}
|
||||
Err(e) => failed = Some(e),
|
||||
}
|
||||
}
|
||||
match failed {
|
||||
Some(e) if !self.failing.swap(true, Ordering::Relaxed) => crate::diag::warn!("access check failed; open connections kept until it works again", group = self.name(), error = e),
|
||||
None if self.failing.swap(false, Ordering::Relaxed) => crate::diag::info!("access check works again", group = self.name()),
|
||||
_ => {}
|
||||
}
|
||||
if removed.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let mut closed = 0;
|
||||
// Taken out as they're closed, so a thread that takes a while to
|
||||
// notice isn't closed and logged again on every recheck.
|
||||
self.open.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, (uid, conn)| {
|
||||
if !removed.contains(uid) {
|
||||
return true;
|
||||
}
|
||||
// Ends the connection for every thread using it: reads see the
|
||||
// end, writes fail, as if the client had hung up.
|
||||
let _ = conn.shutdown(Shutdown::Both);
|
||||
closed += 1;
|
||||
false
|
||||
});
|
||||
for uid in &removed {
|
||||
crate::diag::warn!("connections closed: user is no longer in the access group", group = self.name(), uid = uid);
|
||||
}
|
||||
closed
|
||||
}
|
||||
|
||||
/// Checks everyone connected every few seconds, and writes the access
|
||||
/// list again whenever the group's members change.
|
||||
pub fn watch(self: Arc<Self>) -> io::Result<()> {
|
||||
std::thread::Builder::new().name("kiri-access".into()).spawn(move || {
|
||||
// Unknown at first: the first recheck writes the list once more,
|
||||
// so a change between startup's write and now isn't missed.
|
||||
let mut listed = None;
|
||||
loop {
|
||||
std::thread::sleep(RECHECK);
|
||||
self.tick(&mut listed);
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the socket's access list: its owner and group (rw, as the mode
|
||||
/// says), each of `uids` (rw), nobody else.
|
||||
pub fn set(socket: &Path, uids: &[u32]) -> io::Result<()> {
|
||||
@@ -116,6 +436,124 @@ mod tests {
|
||||
assert_eq!(entries, vec![(1, 6, u32::MAX), (2, 6, 1000), (2, 6, 1001), (4, 6, u32::MAX), (0x10, 6, u32::MAX), (0x20, 0, u32::MAX)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn membership_includes_names_and_primary_group() {
|
||||
let alice = c"alice";
|
||||
let mut names = [alice.as_ptr().cast_mut(), std::ptr::null_mut()];
|
||||
let group = libc::group {
|
||||
gr_name: c"kiri".as_ptr().cast_mut(),
|
||||
gr_passwd: c"x".as_ptr().cast_mut(),
|
||||
gr_gid: 100,
|
||||
gr_mem: names.as_mut_ptr(),
|
||||
};
|
||||
assert!(group_member(alice, 1, &group));
|
||||
assert!(group_member(c"bob", 100, &group));
|
||||
assert!(!group_member(c"bob", 1, &group));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepted_connection_reports_its_peer_uid() {
|
||||
let (a, _b) = UnixStream::pair().unwrap();
|
||||
// SAFETY: getuid cannot fail.
|
||||
assert_eq!(peer_uid(&a).unwrap(), unsafe { libc::getuid() });
|
||||
}
|
||||
|
||||
/// The real lookup, without the root and owner shortcuts. Skipped where
|
||||
/// the test's uid has no account (some CI containers).
|
||||
#[test]
|
||||
fn current_users_primary_group_counts() {
|
||||
// SAFETY: getuid cannot fail.
|
||||
let uid = unsafe { libc::getuid() };
|
||||
let Some(a) = account_by_uid(uid).unwrap() else { return };
|
||||
let g = {
|
||||
// SAFETY: getgrgid_r with a group record and a buffer of the stated size.
|
||||
let gid = a.rec.pw_gid;
|
||||
unsafe { nss(|rec, buf, len, out| libc::getgrgid_r(gid, rec, buf, len, out)) }.unwrap()
|
||||
};
|
||||
let Some(g) = g else { return };
|
||||
// SAFETY: gr_name is a NUL-terminated string in the record's buffer.
|
||||
let name = unsafe { CStr::from_ptr(g.rec.gr_name) }.to_owned();
|
||||
assert!(member(uid, &name).unwrap());
|
||||
assert!(!member(u32::MAX - 7, &name).unwrap(), "no such account");
|
||||
assert!(!member(uid, c"kiri-no-such-group-x").unwrap(), "a deleted group has nobody in it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookups_from_many_threads_agree() {
|
||||
// SAFETY: getuid cannot fail.
|
||||
let uid = unsafe { libc::getuid() };
|
||||
let Some(a) = account_by_uid(uid).unwrap() else { return };
|
||||
// SAFETY: pw_name is a NUL-terminated string in the record's buffer.
|
||||
let me = unsafe { CStr::from_ptr(a.rec.pw_name) }.to_owned();
|
||||
std::thread::scope(|s| {
|
||||
for _ in 0..8 {
|
||||
s.spawn(|| {
|
||||
for _ in 0..200 {
|
||||
let b = account_by_uid(uid).unwrap().unwrap();
|
||||
// SAFETY: as above.
|
||||
assert_eq!(unsafe { CStr::from_ptr(b.rec.pw_name) }, me.as_c_str());
|
||||
assert!(account_by_uid(u32::MAX - 7).unwrap().is_none());
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn gate() -> Arc<Gate> {
|
||||
let mut g = Gate::new(Path::new("/nonexistent"), OsStr::new("kiri")).unwrap();
|
||||
Arc::get_mut(&mut g).unwrap().owner = u32::MAX;
|
||||
g
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_and_the_daemons_own_account_need_no_group() {
|
||||
let g = gate();
|
||||
assert!(g.allowed(0).unwrap());
|
||||
let mut g2 = Gate::new(Path::new("/nonexistent"), OsStr::new("kiri-no-such-group-x")).unwrap();
|
||||
Arc::get_mut(&mut g2).unwrap().owner = 4242;
|
||||
assert!(g2.allowed(4242).unwrap());
|
||||
assert!(!g2.allowed(4243).unwrap(), "anyone else is looked up");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_or_failed_checks_keep_the_connection_out() {
|
||||
let g = gate();
|
||||
let (a, _b) = UnixStream::pair().unwrap();
|
||||
assert!(g.admit_with(&a, |_| Ok(false)).is_none());
|
||||
assert!(g.admit_with(&a, |_| Err(io::Error::other("nss down"))).is_none());
|
||||
assert!(g.open.lock().unwrap().is_empty());
|
||||
let seat = g.admit_with(&a, |_| Ok(true)).unwrap();
|
||||
assert_eq!(g.open.lock().unwrap().len(), 1);
|
||||
drop(seat);
|
||||
assert!(g.open.lock().unwrap().is_empty(), "a closed connection isn't watched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removal_closes_an_open_connection_mid_stream() {
|
||||
use std::io::{Read, Write};
|
||||
let g = gate();
|
||||
let (a, mut b) = UnixStream::pair().unwrap();
|
||||
let _seat = g.admit_with(&a, |_| Ok(true)).unwrap();
|
||||
// A thread blocked reading the client, as an exec session's stdin is.
|
||||
let mut reader = a.try_clone().unwrap();
|
||||
let blocked = std::thread::spawn(move || reader.read(&mut [0; 16]).unwrap());
|
||||
b.write_all(b"x").unwrap();
|
||||
// Still a member: nothing happens.
|
||||
assert_eq!(g.sweep_with(|_| Ok(true)), 0);
|
||||
// A lookup failure keeps it open too.
|
||||
assert_eq!(g.sweep_with(|_| Err(io::Error::other("nss down"))), 0);
|
||||
assert_eq!(blocked.join().unwrap(), 1);
|
||||
let mut reader = a.try_clone().unwrap();
|
||||
let blocked = std::thread::spawn(move || reader.read(&mut [0; 16]).unwrap());
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
// Removed: the blocked read sees the end, and the client does too.
|
||||
assert_eq!(g.sweep_with(|_| Ok(false)), 1);
|
||||
assert_eq!(g.sweep_with(|_| Ok(false)), 0, "closed once, not again on every recheck");
|
||||
assert_eq!(blocked.join().unwrap(), 0);
|
||||
assert_eq!(b.read(&mut [0; 16]).unwrap(), 0);
|
||||
assert!((&a).write_all(b"y").is_err());
|
||||
}
|
||||
|
||||
/// The kernel takes the list and lets a user who isn't in the socket's
|
||||
/// group in by it, at once. Needs root (cargo test -- --ignored, as root).
|
||||
#[test]
|
||||
@@ -126,7 +564,7 @@ mod tests {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let sock = dir.join("s.sock");
|
||||
let _l = std::os::unix::net::UnixListener::bind(&sock).unwrap();
|
||||
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
|
||||
std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o660)).unwrap();
|
||||
// As uid `as_uid` (no groups): can it connect?
|
||||
let try_as = |as_uid: u32| {
|
||||
@@ -148,6 +586,85 @@ mod tests {
|
||||
set(&sock, &[65534]).unwrap();
|
||||
assert!(try_as(65534), "a listed user gets in");
|
||||
assert!(!try_as(65533), "an unlisted one doesn't");
|
||||
set(&sock, &[]).unwrap();
|
||||
assert!(!try_as(65534), "removing the entry takes access away");
|
||||
|
||||
// An old ACL entry is not enough: the daemon's group check still says no.
|
||||
set(&sock, &[65534]).unwrap();
|
||||
assert!(try_as(65534));
|
||||
let (conn, _) = listener.accept().unwrap();
|
||||
let mut gate = Gate::new(&sock, OsStr::new("root")).unwrap();
|
||||
Arc::get_mut(&mut gate).unwrap().owner = u32::MAX;
|
||||
assert!(gate.admit(&conn).is_none(), "nobody is not in root's group");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// A real account, added to a real group and taken out again while
|
||||
/// connected: its open connection is closed and the list rewritten.
|
||||
/// Needs root and useradd (cargo test -- --ignored, as root, in a throwaway system).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn removing_a_real_member_closes_their_connection() {
|
||||
use std::io::Read;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::process::Command;
|
||||
let run = |args: &[&str]| assert!(Command::new(args[0]).args(&args[1..]).status().unwrap().success(), "{args:?}");
|
||||
let _ = Command::new("userdel").arg("kiritest").status();
|
||||
let _ = Command::new("groupdel").arg("kiritestg").status();
|
||||
run(&["groupadd", "kiritestg"]);
|
||||
run(&["useradd", "-M", "-G", "kiritestg", "kiritest"]);
|
||||
let who = uid("kiritest").unwrap();
|
||||
assert!(members("kiritestg").unwrap().contains(&"kiritest".to_owned()));
|
||||
|
||||
let dir = Path::new("/dev/shm").join(format!("kiri-gate-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let sock = dir.join("s.sock");
|
||||
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
|
||||
std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o660)).unwrap();
|
||||
let mut gate = Gate::new(&sock, OsStr::new("kiritestg")).unwrap();
|
||||
Arc::get_mut(&mut gate).unwrap().owner = u32::MAX;
|
||||
assert_eq!(gate.grant().unwrap(), 1);
|
||||
|
||||
// The member connects (by the list: they have no group in this
|
||||
// process) and waits for an answer that never comes.
|
||||
// SAFETY: fork in a test; the child only drops ids, connects, reads and exits.
|
||||
let pid = unsafe {
|
||||
let pid = libc::fork();
|
||||
if pid == 0 {
|
||||
// A gid that isn't the test group, so only the list can let it in.
|
||||
if libc::setgroups(0, std::ptr::null()) != 0 || libc::setgid(65534) != 0 || libc::setuid(who) != 0 {
|
||||
libc::_exit(3);
|
||||
}
|
||||
let code = match std::os::unix::net::UnixStream::connect(&sock) {
|
||||
Ok(mut c) => match c.read(&mut [0; 1]) {
|
||||
Ok(0) => 0,
|
||||
_ => 2,
|
||||
},
|
||||
Err(_) => 1,
|
||||
};
|
||||
libc::_exit(code);
|
||||
}
|
||||
pid
|
||||
};
|
||||
let (conn, _) = listener.accept().unwrap();
|
||||
let _seat = gate.admit(&conn).expect("a member is let in");
|
||||
let mut listed = None;
|
||||
gate.tick(&mut listed);
|
||||
assert_eq!(gate.open.lock().unwrap().len(), 1, "still a member");
|
||||
|
||||
run(&["gpasswd", "-d", "kiritest", "kiritestg"]);
|
||||
gate.tick(&mut listed);
|
||||
assert!(gate.open.lock().unwrap().is_empty(), "removed: their connection is closed");
|
||||
assert_eq!(listed, Some(vec![]), "and the list is written without them");
|
||||
let mut status = 0;
|
||||
// SAFETY: waits for the child forked above.
|
||||
unsafe { libc::waitpid(pid, &mut status, 0) };
|
||||
assert_eq!(libc::WEXITSTATUS(status), 0, "the client saw the connection end");
|
||||
assert_eq!(gate.grant().unwrap(), 0, "and the list no longer names them");
|
||||
|
||||
let _ = Command::new("userdel").arg("kiritest").status();
|
||||
let _ = Command::new("groupdel").arg("kiritestg").status();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
|
||||
@@ -389,7 +389,7 @@ fn images(req: &Request, engine: &Engine) -> Result<Value, Error> {
|
||||
"Id": i.config_digest,
|
||||
"ParentId": "",
|
||||
"RepoTags": [i.name],
|
||||
"RepoDigests": [i.repo_digest()],
|
||||
"RepoDigests": i.repo_digest().into_iter().collect::<Vec<_>>(),
|
||||
"Created": time::parse_unix(&i.created),
|
||||
"Size": i.size,
|
||||
"SharedSize": -1,
|
||||
@@ -409,7 +409,7 @@ fn image_inspect(engine: &Engine, name: &str) -> Result<Value, Error> {
|
||||
Ok(json!({
|
||||
"Id": i.config_digest,
|
||||
"RepoTags": [i.name],
|
||||
"RepoDigests": [i.repo_digest()],
|
||||
"RepoDigests": i.repo_digest().into_iter().collect::<Vec<_>>(),
|
||||
"Created": i.created,
|
||||
"Size": i.size,
|
||||
"Architecture": i.platform.rsplit('/').next().unwrap_or(go_arch()),
|
||||
@@ -455,7 +455,7 @@ fn image_tag(req: &Request, engine: &Engine, source: &str) -> Result<(), Error>
|
||||
let tag = req.query("tag").filter(|t| !t.is_empty()).unwrap_or("latest");
|
||||
let full = format!("{repo}:{tag}");
|
||||
let name = Reference::parse(&full).map(|r| r.short()).map_err(|e| Error::BadRequest(format!("invalid reference format: {e}")))?;
|
||||
engine.store.put_image(kiri_image::Image { name: name.clone(), ..i.clone() })?;
|
||||
engine.store.put_image(i.tagged(name.clone()))?;
|
||||
engine.emit_image("tag", &i.config_digest, &name);
|
||||
Ok(())
|
||||
}
|
||||
@@ -665,6 +665,9 @@ fn push(req: &Request, engine: &Engine, name: &str, w: &mut UnixStream) -> io::R
|
||||
});
|
||||
match result {
|
||||
Ok((digest, size)) => {
|
||||
if let Err(e) = engine.store.set_pushed(&image.name, &image.config_digest, &digest) {
|
||||
crate::diag::warn!("pushed digest not recorded", image = image.name, error = e);
|
||||
}
|
||||
line(json!({"status": format!("{}: digest: {digest} size: {size}", target.reference)}));
|
||||
line(json!({"progressDetail": {}, "aux": {"Tag": target.reference, "Digest": digest, "Size": size}}));
|
||||
}
|
||||
|
||||
@@ -240,6 +240,31 @@ fn write_config(engine: &Engine, id: &str) {
|
||||
if let Err(e) = copy_in(engine, id, "/etc", &mut io::Cursor::new(archive)) {
|
||||
crate::diag::warn!("builder config not written", error = format!("{e:?}"));
|
||||
}
|
||||
if kiri_vmm::rosetta_installed() {
|
||||
hide_amd64_qemu(engine, id);
|
||||
}
|
||||
}
|
||||
|
||||
/// BuildKit's x86-64 emulator, which it runs amd64 build steps under when it
|
||||
/// thinks the machine can't run them itself.
|
||||
const AMD64_QEMU: &str = "buildkit-qemu-x86_64";
|
||||
|
||||
/// With Rosetta shared into the VM, amd64 build steps run through Rosetta,
|
||||
/// as `docker run --platform linux/amd64` does. BuildKit decides whether
|
||||
/// amd64 runs natively by starting a tiny amd64 program in an empty chroot,
|
||||
/// where Rosetta can't start (it needs `/proc/self/exe`), so it would run
|
||||
/// every amd64 step under its own QEMU instead: much slower, and some
|
||||
/// programs crash there (Bun aborts with "MemoryExhaustion"). With no
|
||||
/// executable emulator BuildKit runs the step directly, and the kernel
|
||||
/// hands it to Rosetta, which works inside the step's container. Other
|
||||
/// platforms (arm/v7, riscv64…) keep their emulators. An empty file, not
|
||||
/// executable, takes the emulator's place, so builders made before this
|
||||
/// change get it too.
|
||||
fn hide_amd64_qemu(engine: &Engine, id: &str) {
|
||||
let archive = tar(&[(AMD64_QEMU, Some(&[]))]);
|
||||
if let Err(e) = copy_in(engine, id, "/usr/bin", &mut io::Cursor::new(archive)) {
|
||||
crate::diag::warn!("builder amd64 emulator not hidden", error = format!("{e:?}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST /containers/create` for the builder's name, from buildx when it
|
||||
@@ -1005,6 +1030,17 @@ fn du_rows(text: &str) -> Value {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// BuildKit looks the emulator up by name and skips it when it isn't
|
||||
/// executable, so the file taking its place must be a plain 0644 file.
|
||||
#[test]
|
||||
fn hidden_amd64_emulator_is_not_executable() {
|
||||
let archive = tar(&[(AMD64_QEMU, Some(&[]))]);
|
||||
assert_eq!(&archive[..AMD64_QEMU.len() + 1], format!("{AMD64_QEMU}\0").as_bytes());
|
||||
assert_eq!(&archive[100..108], b"0000644\0");
|
||||
assert_eq!(archive[156], b'0');
|
||||
assert_eq!(&archive[124..136], b"00000000000\0");
|
||||
}
|
||||
|
||||
fn req(query: &[(&str, &str)]) -> Request {
|
||||
Request::internal("POST", "/build", query, Vec::new())
|
||||
}
|
||||
|
||||
@@ -3024,7 +3024,7 @@ mod image_lookup_tests {
|
||||
] {
|
||||
assert!(found(&pulled, &name), "{name}");
|
||||
}
|
||||
assert_eq!(pulled[0].repo_digest(), format!("kindest/node@{INDEX}"));
|
||||
assert_eq!(pulled[0].repo_digest(), Some(format!("kindest/node@{INDEX}")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3041,7 +3041,7 @@ mod image_lookup_tests {
|
||||
#[test]
|
||||
fn an_image_without_an_index_shows_its_manifest_digest() {
|
||||
let pulled = image("alpine:latest", None);
|
||||
assert_eq!(pulled.repo_digest(), format!("alpine@{ARM64}"));
|
||||
assert_eq!(pulled.repo_digest(), Some(format!("alpine@{ARM64}")));
|
||||
assert!(found(&[pulled], &format!("alpine:3@{ARM64}")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,15 +92,26 @@ pub fn run(_args: &[String]) -> io::Result<()> {
|
||||
std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600))?;
|
||||
// On a Linux host the daemon runs as root; `KIRI_SOCKET_GROUP=kiri`
|
||||
// lets that group's users in, as the docker group does for dockerd.
|
||||
if let Some(group) = std::env::var_os("KIRI_SOCKET_GROUP") {
|
||||
socket_group(&socket, &group)?;
|
||||
// And each member by name, so one just added needn't sign in again.
|
||||
#[cfg(target_os = "linux")]
|
||||
match access::grant(&socket, &group.to_string_lossy()) {
|
||||
Ok(n) => diag::info!("socket access list written", members = n),
|
||||
Err(e) => diag::warn!("socket access list not written: new members sign in again first", error = e),
|
||||
}
|
||||
let access_group = std::env::var_os("KIRI_SOCKET_GROUP");
|
||||
if let Some(group) = &access_group {
|
||||
socket_group(&socket, group)?;
|
||||
}
|
||||
// Each member by name too, so one just added needn't sign in again; and
|
||||
// connections are checked against the group when made and while open, so
|
||||
// a member removed is let go at once, whatever the list still says.
|
||||
#[cfg(target_os = "linux")]
|
||||
let gate = match &access_group {
|
||||
Some(group) => {
|
||||
let gate = access::Gate::new(&socket, group)?;
|
||||
match gate.grant() {
|
||||
Ok(n) => diag::info!("socket access list written", members = n),
|
||||
Err(e) => diag::warn!("socket access list not written: new members sign in again first", error = e),
|
||||
}
|
||||
gate.clone().watch()?;
|
||||
Some(gate)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
// SIGINT/SIGTERM shut down cleanly: power the guest off, remove the socket.
|
||||
// Blocked here so every thread inherits it; one thread waits for them.
|
||||
@@ -172,7 +183,19 @@ pub fn run(_args: &[String]) -> io::Result<()> {
|
||||
for conn in listener.incoming() {
|
||||
let Ok(conn) = conn else { continue };
|
||||
let engine = engine.clone();
|
||||
#[cfg(target_os = "linux")]
|
||||
let gate = gate.clone();
|
||||
let spawned = std::thread::Builder::new().name("kiri-api".into()).spawn(move || {
|
||||
// Checked here, not in the accept loop: a slow user lookup holds up
|
||||
// this connection only.
|
||||
#[cfg(target_os = "linux")]
|
||||
let _seat = match &gate {
|
||||
Some(gate) => match gate.admit(&conn) {
|
||||
Some(seat) => Some(seat),
|
||||
None => return,
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let _ = api::serve(conn, engine);
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
|
||||
@@ -74,10 +74,10 @@ pub fn run(autostart: bool, view: Option<String>) -> io::Result<()> {
|
||||
settings.set_hardware_acceleration_policy(webkit2gtk::HardwareAccelerationPolicy::Never);
|
||||
settings.set_enable_write_console_messages_to_stdout(cfg!(debug_assertions));
|
||||
}
|
||||
// The page paints its own background: no white flash before it does.
|
||||
webview.set_background_color(>k::gdk::RGBA::new(0.0, 0.0, 0.0, 0.0));
|
||||
webview.load_html(&super::assemble::page(PAGE), None);
|
||||
window.add(&webview);
|
||||
// Before set_appearance, which gives it its background.
|
||||
WEBVIEW.with(|v| *v.borrow_mut() = Some(webview));
|
||||
|
||||
set_appearance(prefs()["theme"].as_str().unwrap_or("system"));
|
||||
let quit_tx = tx;
|
||||
@@ -87,7 +87,6 @@ pub fn run(autostart: bool, view: Option<String>) -> io::Result<()> {
|
||||
glib::Propagation::Proceed
|
||||
});
|
||||
window.show_all();
|
||||
WEBVIEW.with(|v| *v.borrow_mut() = Some(webview));
|
||||
WINDOW.with(|v| *v.borrow_mut() = Some(window));
|
||||
gtk::main();
|
||||
let _ = engine.join();
|
||||
@@ -142,16 +141,32 @@ pub(super) fn zoom() {
|
||||
pub(super) fn set_appearance(theme: &str) {
|
||||
let theme = theme.to_owned();
|
||||
glib::MainContext::default().invoke(move || {
|
||||
let dark = match theme.as_str() {
|
||||
"dark" => true,
|
||||
"light" => false,
|
||||
_ => desktop_dark(),
|
||||
};
|
||||
if let Some(settings) = gtk::Settings::default() {
|
||||
match theme.as_str() {
|
||||
"dark" => settings.set_gtk_application_prefer_dark_theme(true),
|
||||
"light" => settings.set_gtk_application_prefer_dark_theme(false),
|
||||
_ => settings.set_gtk_application_prefer_dark_theme(desktop_dark()),
|
||||
}
|
||||
settings.set_gtk_application_prefer_dark_theme(dark);
|
||||
}
|
||||
WEBVIEW.with(|v| {
|
||||
if let Some(webview) = v.borrow().as_ref() {
|
||||
webview.set_background_color(&page_background(dark));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The view's background under the page: index.html's `--bg` for the scheme,
|
||||
/// so there is no white flash before the page paints. Opaque on purpose: with
|
||||
/// a transparent view and no GPU compositing (see `run`), WebKitGTK 2.54 keeps
|
||||
/// only the regions repainted in each frame, and the rest of the window
|
||||
/// flickers through to whatever is behind it.
|
||||
fn page_background(dark: bool) -> gtk::gdk::RGBA {
|
||||
let (r, g, b) = if dark { (0x0F, 0x14, 0x19) } else { (0xF5, 0xF7, 0xFA) };
|
||||
gtk::gdk::RGBA::new(f64::from(r) / 255.0, f64::from(g) / 255.0, f64::from(b) / 255.0, 1.0)
|
||||
}
|
||||
|
||||
/// GNOME's (and most desktops') dark preference, through the settings portal's key.
|
||||
fn desktop_dark() -> bool {
|
||||
std::process::Command::new("gsettings")
|
||||
|
||||
@@ -376,7 +376,8 @@ td.r, th.r { text-align: right; }
|
||||
.name { display: flex; align-items: center; gap: 10px; }
|
||||
.tile { width: 30px; height: 30px; border-radius: 8px; display: grid; place-items: center; flex: none; background: var(--raised); color: var(--faint); box-shadow: inset 0 0 0 1px var(--line); }
|
||||
.tile svg { width: 18px; height: 18px; fill: currentColor; }
|
||||
/* A tag never stretches its column: a long one ends in an ellipsis, whole in its title. */
|
||||
/* A tag never stretches its column: a long one ends in an ellipsis, whole in its title.
|
||||
Cap the pill at 160px; Images' Tag cell (td.clip + fixed shares) can clip further when narrow. */
|
||||
.tag.k8s { margin-left: 6px; color: var(--blue); border-color: color-mix(in srgb, var(--blue) 40%, transparent); background: color-mix(in srgb, var(--blue) 10%, transparent); }
|
||||
.k8s-mark { margin-left: 6px; display: inline-flex; vertical-align: -3px; }
|
||||
.k8s-mark svg { width: 16px; height: 16px; fill: #326CE5; }
|
||||
@@ -3419,6 +3420,9 @@ function show(view) {
|
||||
if (view === "share") { send("shares"); send("shareusage"); shPoll(); }
|
||||
if (view === "settings") { if (!fontLists.families.length) send("fonts"); send("about"); send("logins"); send("resources"); send("proxy"); if (!ui.imp.sources) send("importsources"); if (prefs.tab === "diagnostics") diagOpen(); }
|
||||
render();
|
||||
// From the top, as a container's or pod's page opens: leaving a page scrolled
|
||||
// down (a long Terminal or Logs tab) otherwise opened the next view below its rows.
|
||||
$("content").scrollTop = 0;
|
||||
}
|
||||
|
||||
const empty = {
|
||||
@@ -3478,8 +3482,10 @@ function fitColumns() {
|
||||
const fixed = (th) => !!th.dataset.fixed;
|
||||
let w = widths()[tbl.dataset.view];
|
||||
if (w && cells.length !== w.cols.length) w = null;
|
||||
// A table with fixed columns is always laid out here; one without, only once it's been resized.
|
||||
if (!w && !cells.some(fixed)) return;
|
||||
// Laid out when columns declare a share or a fixed width, or after the
|
||||
// person has resized once (saved widths). Share-only tables (Images,
|
||||
// Containers) must not wait for a drag — otherwise a long tag pushes Actions off.
|
||||
if (!w && !cells.some((th) => fixed(th) || th.dataset.share)) return;
|
||||
tbl.classList.add("sized");
|
||||
const box = getComputedStyle(tbl.parentElement);
|
||||
// Actions take what their buttons need, not a saved width: a saved one can be stale or inflated.
|
||||
@@ -4034,8 +4040,8 @@ function renderImages() {
|
||||
const [repo, tag] = untagged(i) ? ["<none>", ""] : split(name);
|
||||
const picked = ui.picked && (i.RepoTags || []).some((t) => t === ui.picked || t === `${ui.picked}:latest`);
|
||||
rows.push(`<tr class="row${picked ? " picked" : ""}${chosen("images", i)}" data-rowopen="img" data-key="${esc(name)}"${pickAt("images", i)}>
|
||||
${pickCell("images", i)}<td><div class="name" data-img="${esc(name)}">${tile(i.icon)}<div><span class="link">${esc(repo)}</span></div></div></td>
|
||||
<td>${untagged(i) ? '<span class="tag none">untagged</span>' : tagPill(tag)}</td>
|
||||
${pickCell("images", i)}<td class="clip"><div class="name" data-img="${esc(name)}" title="${esc(repo)}">${tile(i.icon)}<div><span class="link">${esc(repo)}</span></div></div></td>
|
||||
<td class="clip">${untagged(i) ? '<span class="tag none">untagged</span>' : tagPill(tag)}</td>
|
||||
${usedCell(i, lit)}
|
||||
<td class="mono muted col-id"><span class="sel">${esc(short(i.Id))}</span>${copyBtn(i.Id, "image ID")}</td>
|
||||
<td class="r num">${size(i.Size)}</td>
|
||||
@@ -4047,7 +4053,9 @@ function renderImages() {
|
||||
${ibtn("trash", "Remove", `data-rmi="${esc(name)}"`, "danger")}
|
||||
</div></td></tr>`);
|
||||
}
|
||||
table([["Repository", "", "repo"], ["Tag", "", "tag"], ["Used by", "", "used"], ["ID", "col-id", "id"], ["Size", "r", "size"], ["Created", "col-created", "created"], ["Pulled", "", "pulled"]], rows, "images");
|
||||
// Shares like Containers: the table is always fixed-layout so a long repo or
|
||||
// tag ellipsises instead of pushing Actions off the window.
|
||||
table([["Repository", "", "repo", { share: 3 }], ["Tag", "", "tag", { share: 1.2 }], ["Used by", "", "used", { share: 1.4 }], ["ID", "col-id", "id", { share: 1 }], ["Size", "r", "size", { share: 0.8 }], ["Created", "col-created", "created", { share: 1 }], ["Pulled", "", "pulled", { share: 1 }]], rows, "images");
|
||||
}
|
||||
|
||||
// An image's page: Images › name, with its layers and settings read from Kiri's store.
|
||||
|
||||
@@ -228,8 +228,10 @@ pub(super) fn set_appearance(theme: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the window (after it was closed or hidden) and brings Kiri forward.
|
||||
/// Shows the window (after it was closed or hidden) and brings Kiri forward,
|
||||
/// putting the Dock icon back that closing the window took away.
|
||||
fn show_window(mtm: MainThreadMarker) {
|
||||
NSApplication::sharedApplication(mtm).setActivationPolicy(NSApplicationActivationPolicy::Regular);
|
||||
WINDOW.with(|w| {
|
||||
if let Some(window) = w.borrow().as_ref() {
|
||||
window.makeKeyAndOrderFront(None);
|
||||
@@ -442,9 +444,11 @@ define_class!(
|
||||
unsafe impl NSObjectProtocol for AppDelegate {}
|
||||
|
||||
unsafe impl NSApplicationDelegate for AppDelegate {
|
||||
/// Closing the window leaves Kiri in the menu bar, as OrbStack does.
|
||||
/// Closing the window leaves Kiri in the menu bar only, as the tray
|
||||
/// does on Windows: the Dock icon goes until the window opens again.
|
||||
#[unsafe(method(applicationShouldTerminateAfterLastWindowClosed:))]
|
||||
fn should_terminate_after_last_window(&self, _app: &NSApplication) -> bool {
|
||||
fn should_terminate_after_last_window(&self, app: &NSApplication) -> bool {
|
||||
app.setActivationPolicy(NSApplicationActivationPolicy::Accessory);
|
||||
false
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -41,7 +41,8 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr
|
||||
`save`, `load`, `history`, `search`, `image prune`, `system df`;
|
||||
**amd64 images run through Rosetta**, `--platform` honoured
|
||||
- **Builds**: `docker build` / `buildx build` through BuildKit running in a
|
||||
Kiri container (buildx's docker-container driver), stopped when idle
|
||||
Kiri container (buildx's docker-container driver), stopped when idle;
|
||||
on Apple silicon, amd64 build steps run through Rosetta too
|
||||
- **Compose**: `up`, `down`, `ps`, `logs`, `exec`, multiple networks, events
|
||||
- **Mac integration**: container files at `~/Kiri` in Finder (read-only
|
||||
NFS, always current), SSH agent forwarding at
|
||||
|
||||
@@ -14,7 +14,7 @@ case "$KARCH-$(uname -m)" in
|
||||
arm64-*) cross=aarch64-linux-gnu- pkgs=gcc-aarch64-linux-gnu ;;
|
||||
*) echo "KARCH must be arm64 or x86_64" >&2; exit 1 ;;
|
||||
esac
|
||||
apt-get update -qq && apt-get install -y -qq build-essential flex bison bc libssl-dev libelf-dev curl xz-utils python3 $pkgs >/dev/null
|
||||
apt-get update -qq && apt-get install -y -qq build-essential flex bison bc libssl-dev libelf-dev dwarves curl xz-utils python3 $pkgs >/dev/null
|
||||
cd /build
|
||||
[ -f "linux-$KVER/Makefile" ] && [ -f "linux-$KVER/scripts/Kbuild.include" ] || { rm -rf "linux-$KVER"; curl -fsSL "https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-$KVER.tar.xz" | tar xJ; }
|
||||
cd "linux-$KVER"
|
||||
@@ -34,7 +34,7 @@ missing=0
|
||||
for line in $(grep -E '^CONFIG_[A-Z0-9_]+=y' "$config"); do
|
||||
grep -qx "$line" .config || { echo "MISSING: $line"; missing=1; }
|
||||
done
|
||||
[ "$missing" = 0 ] || echo "some options were not applied (dependency not met)"
|
||||
[ "$missing" = 0 ] || { echo "some options were not applied (dependency not met)" >&2; exit 1; }
|
||||
if [ "$KARCH" = x86_64 ]; then
|
||||
make -s -j"$(nproc)" ARCH=x86_64 CROSS_COMPILE="$cross" bzImage
|
||||
cp arch/x86/boot/bzImage .config /out/
|
||||
|
||||
@@ -32,8 +32,16 @@ CONFIG_HIGH_RES_TIMERS=y
|
||||
CONFIG_NO_HZ_IDLE=y
|
||||
CONFIG_PREEMPT_VOLUNTARY=y
|
||||
CONFIG_PSI=y
|
||||
# /proc/<pid>/io: per-process read and write counts. Programs that read it at
|
||||
# start (Typesense's metrics, monitoring agents) crash or fail without it.
|
||||
CONFIG_TASKSTATS=y
|
||||
CONFIG_TASK_XACCT=y
|
||||
CONFIG_TASK_IO_ACCOUNTING=y
|
||||
# Only root may load BPF programs (kernel.unprivileged_bpf_disabled=2), as on
|
||||
# every major distribution. Cilium and other eBPF tools run as root.
|
||||
CONFIG_BPF_UNPRIV_DEFAULT_OFF=y
|
||||
CONFIG_BPF_SYSCALL=y
|
||||
# CONFIG_BPF_JIT is not set
|
||||
CONFIG_BPF_JIT=y
|
||||
CONFIG_KEYS=y
|
||||
CONFIG_SECCOMP=y
|
||||
CONFIG_SECCOMP_FILTER=y
|
||||
@@ -499,3 +507,18 @@ CONFIG_INET_IPCOMP=y
|
||||
CONFIG_INET6_AH=y
|
||||
CONFIG_INET6_ESP=y
|
||||
CONFIG_INET6_IPCOMP=y
|
||||
|
||||
# --- eBPF tools: Cilium, bpftrace, Tetragon -----------------------------------
|
||||
# With BPF_JIT above. Perf events carry the datapath's drop and trace events
|
||||
# (bpf_perf_event_output); BPF_EVENTS follows from perf events plus kprobe
|
||||
# events. BTF (/sys/kernel/btf/vmlinux) needs debug info and pahole at build
|
||||
# time; the debug info itself is not in the Image. SHA1 is on Cilium's list;
|
||||
# the IPsec options above select SHA256 only.
|
||||
CONFIG_PERF_EVENTS=y
|
||||
CONFIG_FTRACE=y
|
||||
CONFIG_KPROBES=y
|
||||
CONFIG_KPROBE_EVENTS=y
|
||||
CONFIG_DEBUG_KERNEL=y
|
||||
CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT=y
|
||||
CONFIG_DEBUG_INFO_BTF=y
|
||||
CONFIG_CRYPTO_SHA1=y
|
||||
@@ -593,9 +593,14 @@ t login-wrong "incorrect username or password" bash -c "echo nope | $R login loc
|
||||
t login "Login Succeeded" bash -c "echo kiripass | $R login localhost:5055 -u kiriuser --password-stdin 2>&1"
|
||||
t push "digest: sha256:" bash -c "$R tag alpine localhost:5055/team/alp:1 && $R push localhost:5055/team/alp:1 2>&1"
|
||||
t push-again "already exists" bash -c "$R push localhost:5055/team/alp:1 2>&1"
|
||||
# Deploy tools pin to the RepoDigest after a push: it must be the manifest the
|
||||
# registry has, not the image ID or the index alpine was pulled from.
|
||||
t push-repo-digest "same" bash -c "d=\$($R push localhost:5055/team/alp:1 2>&1 | sed -n 's/.*digest: \(sha256:[0-9a-f]*\).*/\1/p'); [ -n \"\$d\" ] && [ \"\$($R image inspect localhost:5055/team/alp:1 --format '{{index .RepoDigests 0}}')\" = localhost:5055/team/alp@\$d ] && echo same"
|
||||
t pull-auth "3." bash -c "$R rmi localhost:5055/team/alp:1 >/dev/null && $R pull -q localhost:5055/team/alp:1 >/dev/null && $R run --rm localhost:5055/team/alp:1 cat /etc/alpine-release"
|
||||
t pull-no-auth "pull access denied" bash -c "$R logout localhost:5055 >/dev/null; $R rmi localhost:5055/team/alp:1 >/dev/null; $R pull localhost:5055/team/alp:1 2>&1"
|
||||
t push-no-auth "authentication required" bash -c "$R tag alpine localhost:5055/team/alp:2 && $R push localhost:5055/team/alp:2 2>&1"
|
||||
# Not pushed, so no RepoDigest: not alpine's from Docker Hub, nor one made up.
|
||||
t push-failed-no-digest "[]" $R image inspect localhost:5055/team/alp:2 --format '{{json .RepoDigests}}'
|
||||
$D rmi localhost:5055/team/alp:2 >/dev/null 2>&1; $D rm -f reg >/dev/null; rm -rf "$REG"
|
||||
|
||||
section "limits, stats, top, pause, update"
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
// Images: a long repository or tag must not push Actions' buttons past the
|
||||
// column — the list always uses fixed column shares, like Containers.
|
||||
const R = [];
|
||||
const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } };
|
||||
const nowS = Date.now() / 1000;
|
||||
kiri.on({ type: "lists", containers: [], images: [
|
||||
{ Id: "sha256:" + "a".repeat(64), RepoTags: ["harbor.example.com:9090/szda/very-long-path/rustfs:arm-1.0.0-beta.8-extra-long"], Size: 1e8, Created: nowS - 60, Pulled: nowS - 30 },
|
||||
{ Id: "sha256:" + "b".repeat(64), RepoTags: ["nginx:alpine"], Size: 1e7, Created: nowS - 120, Pulled: nowS - 90 },
|
||||
], volumes: [], networks: [] });
|
||||
document.body.style.width = "1100px";
|
||||
show("images");
|
||||
|
||||
t("Images is laid out with fixed shares without a prior resize", () => {
|
||||
const tbl = document.querySelector("#content table[data-view=images]");
|
||||
if (!tbl?.classList.contains("sized")) throw new Error("not sized");
|
||||
if (![...tbl.tHead.rows[0].cells].some((th) => th.dataset.share)) throw new Error("no shares on headings");
|
||||
});
|
||||
t("a long tag and repository leave every Actions button inside its column", () => {
|
||||
const tbl = document.querySelector("#content table.sized");
|
||||
for (const r of tbl.tBodies[0].rows) {
|
||||
const td = r.cells[r.cells.length - 1];
|
||||
if (!td.classList.contains("actions")) throw new Error("last cell is not actions");
|
||||
const colR = td.getBoundingClientRect().right;
|
||||
for (const b of td.querySelectorAll("button")) {
|
||||
if (b.getBoundingClientRect().right > colR + 0.5) throw new Error(`button past column: ${b.getAttribute("aria-label")}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
t("the long tag is clipped with its full value in the title", () => {
|
||||
const pill = document.querySelector('#content tr[data-key*="rustfs"] .tag');
|
||||
if (!pill) throw new Error("no tag pill");
|
||||
if (!/arm-1\.0\.0-beta\.8/.test(pill.title)) throw new Error("title missing full tag: " + pill.title);
|
||||
if (pill.scrollWidth <= pill.clientWidth + 1 && pill.textContent.length > 20) {
|
||||
// May or may not overflow depending on column share; the cell must still clip.
|
||||
}
|
||||
const cell = pill.closest("td");
|
||||
if (!cell.classList.contains("clip")) throw new Error("tag cell not clip");
|
||||
});
|
||||
report(R);
|
||||
Reference in new issue
Block a user