diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6f643d8..374e882 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -121,6 +121,46 @@ jobs: target/release/bundle/rpm/*.rpm target/release/bundle/appimage/*.AppImage + # Arch package for the pacman repository on Gitea, built from the deb. + # Needs the secret GITEA_PACKAGES_TOKEN (a Gitea token with package write + # access); without it the job is skipped. + arch: + if: startsWith(github.ref, 'refs/tags/v') + needs: [linux] + runs-on: ubuntu-latest + container: archlinux:latest + env: + TOKEN: ${{ secrets.GITEA_PACKAGES_TOKEN }} + REGISTRY: https://git.joshicodes.de/api/packages/JoshiCodes/arch/joshicodes + steps: + - uses: actions/checkout@v5 + - uses: actions/download-artifact@v5 + with: + name: linux + path: artifacts + - name: Build knock-bin + if: env.TOKEN != '' + run: | + pacman -Syu --noconfirm --needed base-devel + useradd -m builder + deb=$(find artifacts -name '*.deb' | head -1) + tag="${GITHUB_REF_NAME#v}" + ver="${tag//-/}" + mkdir -p /build && cp packaging/arch/knock-bin/PKGBUILD /build/ && cp "$deb" /build/ + cd /build + name=$(basename "$deb") + sed -i -E "s/^pkgver=.*/pkgver=$ver/; s/^pkgrel=.*/pkgrel=1/" PKGBUILD + sed -i -E "s|^source=.*|source=(\"$name\")|" PKGBUILD + chown -R builder /build + su builder -c 'makepkg --nodeps --noconfirm' + ls -la *.pkg.tar.zst + - name: Upload to the Gitea pacman repository + if: env.TOKEN != '' + run: | + for f in /build/*.pkg.tar.zst; do + curl --fail-with-body -sS -X PUT --user "JoshiCodes:$TOKEN" --upload-file "$f" "$REGISTRY" + done + release: if: startsWith(github.ref, 'refs/tags/v') needs: [macos, linux, windows] diff --git a/README.md b/README.md index bed2ae9..38c12f2 100644 --- a/README.md +++ b/README.md @@ -68,13 +68,56 @@ knock auth debug users --env prod --verbose ## Install -- **Arch Linux / CachyOS:** `packaging/arch/knock-bin` (release package), `packaging/arch/knock` (from source) or `packaging/arch/knock-git` (latest `main`); `makepkg -si` in the folder -- **Ubuntu 22.04+ / Debian:** the `.deb` from the [latest release](https://github.com/JoshiCodes/knock/releases/latest) -- **Fedora and others:** the `.rpm` or the AppImage -- **macOS:** the universal `.dmg` (not notarized: open it once with right click → Open) -- **Windows:** the `.msi` or setup `.exe` (best effort) +Downloads are on the [releases page](https://github.com/JoshiCodes/knock/releases/latest). Every package contains the app (`knock-app`) and the command line tool (`knock`). -If the window stays blank on Wayland, WebKitGTK's DMA-BUF renderer is the usual cause; knock turns it off by default. Set `KNOCK_DMABUF=1` to turn it back on. +### Arch Linux, CachyOS, Manjaro + +From the pacman repository (signed). Once: + +```sh +curl -fsSL https://git.joshicodes.de/api/packages/JoshiCodes/arch/repository.key | sudo pacman-key --add - && sudo pacman-key --lsign-key B500A6315A9D97708BF6241F10CECFC71020FEB1 +printf '\n[joshicodes]\nServer = https://git.joshicodes.de/api/packages/JoshiCodes/arch/$repo/$arch\n' | sudo tee -a /etc/pacman.conf >/dev/null && sudo pacman -Sy knock-bin +``` + +Updates then come with `sudo pacman -Syu`. Building yourself: `makepkg -si` in `packaging/arch/knock` (release from source) or `packaging/arch/knock-git` (latest `main`). + +### Ubuntu 22.04+, Debian, Linux Mint, Pop!_OS + +Download `knock__amd64.deb` from the release and install it: + +```sh +sudo apt install ./knock_*_amd64.deb +``` + +### Fedora, openSUSE + +```sh +sudo dnf install ./knock-*.x86_64.rpm # openSUSE: sudo zypper install ./knock-*.x86_64.rpm +``` + +### Any other Linux + +The AppImage runs without installing: + +```sh +chmod +x knock_*_amd64.AppImage && ./knock_*_amd64.AppImage +``` + +It needs `libsecret` (or another Secret Service) for secrets. If the window stays blank on Wayland, start it with `WEBKIT_DISABLE_DMABUF_RENDERER=1` (the packages set this already). + +### macOS + +Open the universal `knock__universal.dmg` (Apple Silicon and Intel) and drag knock to Applications. The app is not notarized by Apple, so macOS blocks the first start. Allow it once: + +```sh +xattr -dr com.apple.quarantine /Applications/knock.app +``` + +(or System Settings → Privacy & Security → **Open Anyway** after the first attempt). The command line tool is in `knock-cli-macos-universal.tar.gz`: unpack it and move `knock` to a folder on your `PATH`, e.g. `/usr/local/bin`. + +### Windows (best effort) + +Run the `.msi` or the setup `.exe`. Windows SmartScreen warns about apps without a code signing certificate: click **More info → Run anyway**. The command line tool is in `knock-cli-windows-x64.zip`. ## Development diff --git a/crates/knock-core/src/http.rs b/crates/knock-core/src/http.rs index 9e396b8..237d802 100644 --- a/crates/knock-core/src/http.rs +++ b/crates/knock-core/src/http.rs @@ -135,6 +135,18 @@ impl Engine { } } + /// Ids of loaded jars that belong to a collection (its own and its folders'). + pub fn jar_ids(&self, collection: &str) -> Vec { + let prefix = format!("{collection}/"); + self.jars + .lock() + .unwrap() + .keys() + .filter(|k| *k == collection || k.starts_with(&prefix)) + .cloned() + .collect() + } + pub fn save_jar(&self, collection: &str) -> String { let jar = self.jar(collection); let store = jar.lock().unwrap(); diff --git a/crates/knock-core/src/model.rs b/crates/knock-core/src/model.rs index 4a773d5..83a7982 100644 --- a/crates/knock-core/src/model.rs +++ b/crates/knock-core/src/model.rs @@ -158,10 +158,23 @@ pub struct FolderMeta { pub headers: Vec, #[serde(default, skip_serializing_if = "IndexMap::is_empty")] pub vars: IndexMap, + /// Cookie jar for this folder and everything below it. Unset shares the + /// jar of the parent (in the end the collection's). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cookies: Option, #[serde(flatten)] pub extra: Extra, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum CookieJarMode { + /// A jar of its own, separate from the collection's. + Own, + /// No cookies are stored or sent. + Off, +} + // ---------------------------------------------------------------- request #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/knock-core/src/prepare.rs b/crates/knock-core/src/prepare.rs index e78f9da..bce31ef 100644 --- a/crates/knock-core/src/prepare.rs +++ b/crates/knock-core/src/prepare.rs @@ -36,6 +36,9 @@ pub struct RequestContext { pub collection_settings: CollectionSettings, pub collection_id: String, pub env: Option, + /// Cookie jar for this request, from the collection setting and the + /// closest folder that sets one; None means no cookies. + pub jar: Option, } pub struct ContextInput<'a> { @@ -83,6 +86,7 @@ impl RequestContext { } let auth = effective_auth(c, input.request_id, &input.request.auth, &ancestors); + let jar = cookie_jar(&c.manifest.id, c.manifest.settings.cookies, &ancestors); let mut inherited_headers = c.manifest.headers.clone(); for (_, meta) in &ancestors { inherited_headers.extend(meta.headers.iter().cloned()); @@ -95,6 +99,7 @@ impl RequestContext { collection_settings: c.manifest.settings.clone(), collection_id: c.manifest.id.clone(), env: input.env.map(str::to_string), + jar, }) } @@ -119,10 +124,28 @@ impl RequestContext { collection_settings: CollectionSettings::default(), collection_id: String::new(), env: None, + jar: None, } } } +/// The jar id a request uses: the collection id, or `/` +/// for a folder with a jar of its own. +pub fn cookie_jar(collection_id: &str, collection_cookies: bool, ancestors: &[(String, FolderMeta)]) -> Option { + if collection_id.is_empty() { + return None; + } + let mut jar = collection_cookies.then(|| collection_id.to_string()); + for (id, meta) in ancestors { + match meta.cookies { + Some(CookieJarMode::Own) => jar = Some(format!("{collection_id}/{id}")), + Some(CookieJarMode::Off) => jar = None, + None => {} + } + } + jar +} + pub fn effective_auth( c: &Collection, request_id: &str, @@ -540,6 +563,17 @@ mod tests { assert_eq!(path_param_names("http://h:8080/u/:id/:other?x=:no"), vec!["id", "other"]); } + #[test] + fn cookie_jar_follows_the_closest_folder() { + let f = |id: &str, mode: Option| (id.to_string(), FolderMeta { cookies: mode, ..Default::default() }); + assert_eq!(cookie_jar("c", true, &[]), Some("c".into())); + assert_eq!(cookie_jar("c", false, &[]), None); + assert_eq!(cookie_jar("c", true, &[f("oidc", Some(CookieJarMode::Off))]), None); + assert_eq!(cookie_jar("c", true, &[f("web", Some(CookieJarMode::Own)), f("web/admin", None)]), Some("c/web".into())); + assert_eq!(cookie_jar("c", false, &[f("web", Some(CookieJarMode::Own))]), Some("c/web".into())); + assert_eq!(cookie_jar("c", true, &[f("web", Some(CookieJarMode::Own)), f("web/x", Some(CookieJarMode::Off))]), None); + } + #[test] fn jsonc() { let s = "{\n // c\n \"a\": \"http://x\", /* b */\n \"b\": [1,2,],\n}"; diff --git a/crates/knock-core/src/run.rs b/crates/knock-core/src/run.rs index dafdce0..e47e63b 100644 --- a/crates/knock-core/src/run.rs +++ b/crates/knock-core/src/run.rs @@ -27,6 +27,8 @@ pub struct RunOutput { pub missing: Vec, /// The request was sent a second time after refreshing an expired token. pub retried: bool, + /// Cookie jar the request used, if any. + pub jar: Option, } impl RunOutput { @@ -111,6 +113,7 @@ pub async fn execute( error: None, missing: Vec::new(), retried: false, + jar: if req.settings.cookies { ctx.jar.clone() } else { None }, }; let base = match prepare(req, ctx) { Ok(p) => p, @@ -133,8 +136,7 @@ pub async fn execute( return out; } let transport = transport_for(ctx, &p.url); - let jar = (ctx.collection_settings.cookies && !ctx.collection_id.is_empty()) - .then_some(ctx.collection_id.as_str()); + let jar = ctx.jar.as_deref(); match engine.send(&p, &transport, jar).await { Ok(resp) if is_digest && resp.status == 401 => { let challenge = resp diff --git a/packaging/arch/knock-bin/PKGBUILD b/packaging/arch/knock-bin/PKGBUILD index b9df389..02adfca 100644 --- a/packaging/arch/knock-bin/PKGBUILD +++ b/packaging/arch/knock-bin/PKGBUILD @@ -15,5 +15,9 @@ sha256sums=('SKIP') package() { bsdtar -xf data.tar.* -C "$pkgdir" + # KDE matches the window (app id knock-app) to the desktop file by name. + if [ -f "$pkgdir/usr/share/applications/knock.desktop" ]; then + mv "$pkgdir/usr/share/applications/knock.desktop" "$pkgdir/usr/share/applications/knock-app.desktop" + fi install -Dm644 "$pkgdir/usr/share/doc/knock/copyright" "$pkgdir/usr/share/licenses/$pkgname/LICENSE" 2>/dev/null || true } diff --git a/scripts/release.sh b/scripts/release.sh index 387469d..4a2128f 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -33,7 +33,8 @@ sed -i -E "s/^pkgver=.*/pkgver=$base/; s/^pkgrel=.*/pkgrel=1/" packaging/arch/kn cargo update -w --offline >/dev/null 2>&1 || cargo update -w >/dev/null git add Cargo.toml Cargo.lock package.json package-lock.json src-tauri/tauri.conf.json packaging/arch -git commit -q -m "Release v$v" +# The version may already be set (first release); then there is nothing to commit. +git diff --cached --quiet || git commit -q -m "Release v$v" git tag -a "v$v" -m "knock $v" git push -q origin main "v$v" echo "Pushed v$v. Follow the build: gh run watch \$(gh run list -w release -L1 --json databaseId -q '.[0].databaseId')" diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index faa7995..b6f67e8 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -60,8 +60,8 @@ fn remember_recent(state: &AppState, root: &str) { fn register(app: &AppHandle, state: &AppState, c: Collection) -> Res { let v = view(&c); - if let Ok(Some(json)) = db::jar_load(&state.db.lock().unwrap(), &v.id) { - state.engine.load_jar(&v.id, &json); + for (id, json) in db::jars_for(&state.db.lock().unwrap(), &v.id).unwrap_or_default() { + state.engine.load_jar(&id, &json); } let root = c.root.clone(); state.collections.write().unwrap().insert(v.id.clone(), c); @@ -433,9 +433,9 @@ pub async fn request_send(app: AppHandle, args: SendArgs) -> Res { state.set_runtime(&col_key, &x.var, Some(v.clone()), x.persist); } } - if let Some(col) = &args.scope.col { - let json = state.engine.save_jar(col); - let _ = db::jar_save(&state.db.lock().unwrap(), col, &json); + if let Some(jar) = &out.jar { + let json = state.engine.save_jar(jar); + let _ = db::jar_save(&state.db.lock().unwrap(), jar, &json); } let mut body_id = None; @@ -666,8 +666,10 @@ pub async fn runner_run( for (k, v) in &report.runtime { state.set_runtime(&col, k, Some(v.clone()), false); } - let json = state.engine.save_jar(&col); - let _ = db::jar_save(&state.db.lock().unwrap(), &col, &json); + for jar in state.engine.jar_ids(&col) { + let json = state.engine.save_jar(&jar); + let _ = db::jar_save(&state.db.lock().unwrap(), &jar, &json); + } Ok(RunResult { json: knock_core::runner::to_json(&report), junit: knock_core::runner::to_junit(&report), report }) } diff --git a/src-tauri/src/db.rs b/src-tauri/src/db.rs index d2f44d4..5516c7c 100644 --- a/src-tauri/src/db.rs +++ b/src-tauri/src/db.rs @@ -182,10 +182,11 @@ pub fn history_delete(c: &Connection, id: Option) -> Result<()> { Ok(()) } -pub fn jar_load(c: &Connection, collection: &str) -> Result> { - Ok(c - .query_row("SELECT json FROM cookie_jars WHERE collection = ?1", [collection], |r| r.get(0)) - .optional()?) +/// The collection's jar and the jars of its folders (`/`). +pub fn jars_for(c: &Connection, collection: &str) -> Result> { + let mut stmt = c.prepare("SELECT collection, json FROM cookie_jars WHERE collection = ?1 OR collection LIKE ?1 || '/%'")?; + let rows = stmt.query_map([collection], |r| Ok((r.get(0)?, r.get(1)?)))?; + Ok(rows.collect::>()?) } pub fn jar_save(c: &Connection, collection: &str, json: &str) -> Result<()> { diff --git a/src/lib/types.ts b/src/lib/types.ts index f206df7..2435e97 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -146,6 +146,7 @@ export interface FolderMeta { auth?: Auth; headers?: KeyValue[]; vars?: Record; + cookies?: 'own' | 'off'; [extra: string]: unknown; } @@ -308,6 +309,7 @@ export interface RunOutput { error: string | null; missing: string[]; retried: boolean; + jar?: string | null; } export interface SendResult { output: RunOutput; diff --git a/src/lib/views/response/HeadersView.svelte b/src/lib/views/response/HeadersView.svelte index 9217790..40e1836 100644 --- a/src/lib/views/response/HeadersView.svelte +++ b/src/lib/views/response/HeadersView.svelte @@ -9,8 +9,12 @@ let resp = $derived(out.response); let jar = $state([]); + // The jar the request used: the collection's, a folder's own, or none. + let jarId = $derived(out.jar ?? null); + let jarLabel = $derived(!jarId ? null : jarId.includes('/') ? `folder ${jarId.slice(jarId.indexOf('/') + 1)}` : 'collection'); + async function loadJar() { - if (tab.col) jar = await api.cookies(tab.col); + jar = jarId ? await api.cookies(jarId) : []; } $effect(() => { if (cookies) { @@ -20,8 +24,8 @@ }); async function del(c?: CookieInfo) { - if (!tab.col) return; - await api.cookieDelete(tab.col, c); + if (!jarId) return; + await api.cookieDelete(jarId, c); loadJar(); } @@ -55,9 +59,11 @@ {c.domain}{c.path} {c.http_only ? 'HttpOnly' : ''} {c.secure ? 'Secure' : ''} {c.same_site ?? ''} {/each} - {#if tab.col} + {#if !jarId && tab.col} +

This request uses no cookie jar (turned off for the request, its folder or the collection).

+ {:else if jarId}
- Cookie jar of this collection + Cookie jar: {jarLabel} {#if jar.length}{/if}
{#if !jar.length}

Empty.

{/if} diff --git a/src/lib/views/settings/FolderView.svelte b/src/lib/views/settings/FolderView.svelte index 4af13c4..75d6f28 100644 --- a/src/lib/views/settings/FolderView.svelte +++ b/src/lib/views/settings/FolderView.svelte @@ -69,6 +69,18 @@

Requests in this folder that use "inherit" get this auth.

+
+

Cookies

+

A folder can keep its own cookies, for example a frontend session apart from OIDC tests. Sub folders follow unless they choose something else.

+
+ {#each [[undefined, 'Share the cookie jar of the parent folder or collection'], ['own', 'Own cookie jar for this folder'], ['off', 'No cookies']] as [mode, label]} + + {/each} +
+

Headers