Wednesday, December 2, 2026

Linux shell redirection without memorizing 2>&1

cmd >/dev/null 2>&1 is one of those shell expressions people memorize long before they understand it. That works — until the order changes, a pipeline hides a failure, or a script runs under /bin/sh instead of Bash.

Full reference: Linux shell redirection cheatsheet

The three numbers behind the syntax

Every process starts with three conventional file descriptors:

  • 0 — stdin: input, normally the keyboard
  • 1 — stdout: normal output, normally the terminal
  • 2 — stderr: diagnostics, normally the terminal

The shell rewires these descriptors before it starts the command. That single model explains almost every redirection expression.

The recipes you actually need

cmd >output.log             # stdout to file (overwrite)
cmd >>output.log            # stdout to file (append)
cmd 2>error.log             # stderr to file
cmd >output.log 2>error.log # keep them separate
cmd >combined.log 2>&1     # both to one file
cmd >/dev/null             # discard stdout only
cmd 2>/dev/null            # discard stderr only
cmd >/dev/null 2>&1       # discard both

/dev/null is a data sink: writes succeed and disappear. Reading it immediately returns end-of-file.

The trap: order matters

This sends both streams to the file:

cmd >combined.log 2>&1

Read it left to right: first stdout (FD 1) points to the file; then 2>&1 copies stdout's current destination onto stderr.

Reverse the order and the result changes:

cmd 2>&1 >output.log

Stderr copies stdout while stdout still points at the terminal. Then stdout moves to the file. Result: stdout is logged, stderr stays visible. 2>&1 is a snapshot of a destination, not a permanent link.

Pipes carry stdout, not stderr

cmd | less              # stdout only
cmd 2>&1 | less        # stdout + stderr (portable)
cmd |& less             # Bash/zsh shorthand
cmd 2>&1 | tee run.log # show and save both

For Bash automation, pair pipelines with set -o pipefail. Otherwise cmd | tee run.log can report success merely because tee succeeded, even when cmd failed.

Portable shell vs convenient shell

Bash and zsh provide compact forms:

cmd &>combined.log
cmd &>>combined.log
cmd |& less
cmd <<<"one line"

But &>, |&, and here-strings aren't POSIX. If a script may run under /bin/sh, prefer >file 2>&1, 2>&1 |, and heredocs.

Good scripting habits

  • Send machine-readable data to stdout and diagnostics to stderr: printf '%s\n' "warning" >&2.
  • Suppress output only when the exit status is all you need: if command -v jq >/dev/null 2>&1; then ....
  • Don't hide build or deployment failures with >/dev/null 2>&1; log stderr instead.
  • For detached jobs, redirect all three streams: nohup cmd >run.log 2>&1 </dev/null &. Use a service manager for real services.

The mental model worth remembering

  • >/< connect a descriptor to a file.
  • n>&m copies descriptor m's current destination to n.
  • n>&- closes descriptor n.
  • | connects the left process's stdout to the right process's stdin.
  • The shell performs all wiring from left to right before launching the command.

Once you picture file descriptors as wires, >/dev/null 2>&1 stops being punctuation and starts being readable.

The OIDC relying party, built twice: confidential vs public client

Part 3 of the OIDC series. Last time we built the server side of the handshake; this is the other half — the relying party. I built it twice: once the "enterprise default" way (Spring Security OAuth2 client, server-side sessions, Thymeleaf), and once the "modern default" way (React + TypeScript SPA doing Authorization Code + PKCE in the browser). The contrast between the two is the real lesson.

The confidential client: almost boringly easy

Spring Security's OAuth2 client stack turns login into nearly zero lines of code. Point spring.security.oauth2.client.provider at the issuer URI, register client-id/client-secret/redirect URI, and the framework handles the entire authorization-code dance: the 302 to /authorize, the code exchange at /token, ID-token signature validation against JWKS, and the session.

From there the interesting parts are the edges:

  • Logout isn't just clearing a cookie. Killing the local session while the provider session lives means the next "log in" silently succeeds — no password prompt. RP-initiated logout (/connect/logout with an id_token_hint) ends the upstream session too. OidcClientInitiatedLogoutSuccessHandler wires it in three lines, but you have to know it exists.
  • Refresh tokens just work — confidentially. Because the client authenticates with its secret at the token endpoint, the provider happily issues and rotates refresh tokens. "Refresh now" → new access token, old refresh rotated out. The server-side session keeps all of it off the wire.
  • UserInfo vs ID-token claims. Both render user data, but they answer different questions: the ID token is what the provider asserted at login time; /userinfo is what it asserts now, fetched fresh with the access token.

The public client: where the training wheels come off

The React SPA (demo-spa, registered with clientAuthenticationMethod: none) can't hold a secret — anything shipped to the browser is public by definition. So the whole flow becomes your code:

  • PKCE is mandatory, and you implement it. Web Crypto generates the verifier, SHA-256 + base64url produces the code_challenge (S256), and the verifier rides along at the token exchange. The provider enforces requireProofKey — no verifier, no token.
  • state and nonce are your job now. Spring Security validated these invisibly for the confidential client; in the SPA you're generating, stashing (sessionStorage), and verifying both yourself — CSRF on the redirect and token replay are real attacks here.
  • No refresh tokens for public clients. My provider refuses to issue them to NONE-auth clients — a refresh token in browser storage is a long-lived credential an XSS away from exfiltration. Access token expires → sign in again. (The code still implements the refresh path for providers that do allow it.)
  • CORS becomes a protocol concern. The browser calls /token cross-origin, so the provider needs an explicit origin allowlist for its public endpoints — and "credentials: never" stays non-negotiable.

The takeaway the two implementations teach

Confidential vs public isn't just a checkbox in client registration — it's two different threat models:

  • Confidential clients move trust to the backend: secrets stay server-side, tokens live in the session, the browser sees only a cookie.
  • Public clients keep everything in the hostile environment: PKCE proves continuity of the request, state/nonce prove integrity, and the mitigation for "no safe storage" is simply shorter-lived tokens and no refresh.

Building both against the same provider also exposed a real design decision on the server side: the provider must know which clients are public and refuse them refresh tokens — that policy isn't free, it's a registration-time property (publicClient: true → NONE auth + enforced PKCE).

Next: the edge gateway — validating tokens you didn't issue, where JWKS caching, audience checks, and trusted headers get interesting.

Tuesday, December 1, 2026

Spring Authorization Server: from zero to a working OIDC provider

Part 2 of the OIDC series. This is the piece everything else hangs off: standing up a real authorization server with Spring Authorization Server (SAS), and learning where the framework ends and your responsibility begins.

What SAS gives you for free

Drop spring-boot-starter-oauth2-authorization-server on the classpath, register a client, and you immediately get the full protocol surface:

  • /.well-known/openid-configuration — discovery, generated correctly
  • /oauth2/authorize, /oauth2/token, /oauth2/jwks, /oauth2/introspect, /oauth2/revoke, /userinfo
  • Authorization Code + PKCE, Refresh Token, Client Credentials grants
  • A consent screen when a client asks for scopes the user hasn't approved

The honest surprise: the protocol endpoints are the easy 20%. SAS is deliberately a protocol engine, not a product — everything around the endpoints is yours to build.

The four repositories that make it real

SAS's default wiring is in-memory — restart and every client, token, and consent evaporates. Persistence means backing four contracts with real storage (JDBC implementations ship with SAS; Flyway migrates the schema):

  • RegisteredClientRepository → oauth2_registered_client — who may ask for tokens, how, and which grant types/scopes they're allowed
  • OAuth2AuthorizationService → oauth2_authorization — every issued token's server-side record (this is what makes revocation work)
  • OAuth2AuthorizationConsentService → oauth2_authorization_consent — "alice approved demo-web for api:read", remembered
  • Your own UserDetailsService → users/authorities — SAS has no user store; you bring it

What nobody warns you about

The gaps between "running SAS" and "running an IdP":

  • Signing keys. SAS generates an ephemeral RSA key at boot — restart invalidates every token in flight. Production needs keys in a table (oidc_signing_keys), wrapped under a KEK env var, with scheduled rotation and a JWKS read cache that keeps serving the last good set through a DB blip.
  • The sub claim. The obvious mapping — username as sub — is a latent account-confusion bug. sub must be an immutable identifier (UUID column, backfilled by migration); the username stays in preferred_username.
  • Two security domains, not one. Your IdP has a browser surface (login form, admin UI — session cookies, CSRF on) and a protocol surface (token endpoints, admin API — stateless, Basic/bearer, CSRF off, 401 not redirect). Mixing them is how "CSRF disabled for convenience" becomes an actual hole.
  • Client auth method matters. client_secret_post puts secrets in request bodies — which land in access logs. Register clients with client_secret_basic only, and migrate old rows to match.
  • Rate limiting is on you. Every credential endpoint (/login, /oauth2/token, /introspect, /userinfo) is a brute-force surface. Per-IP throttling — Redis-backed if you run replicas, per-instance otherwise — isn't optional.

The dev-loop trick that pays for itself

A dev profile on embedded H2 with seeded data — demo users (alice/password), a confidential web client, an M2M service client — means the entire login roundtrip is one mvn spring-boot:run away. It also keeps the prod profile honest: prod gets a startup validator that refuses to boot on missing env vars rather than silently falling back to dev secrets.

Verifying it end to end

Once the provider runs, the first real test is a full authorization-code roundtrip against the relying party (Part 3):

  1. Browser hits the client app → redirected to /oauth2/authorize
  2. Login form → consent screen → redirect back with ?code=
  3. Client exchanges code at /oauth2/token → ID token + access token
  4. /userinfo returns sub = UUID, preferred_username = alice

Watching your own server complete that handshake is the moment the protocol stops being folklore.

Next: the other side of the handshake — building the relying party, and what Spring Security's OAuth2 client handles vs. what it leaves to you.

Building your own OIDC provider: what the server side actually teaches you

Nobody needs to build their own identity provider. Keycloak, Auth0, Entra ID — the mature options are right there. I built one anyway, and it's the most instructive side project I've run in years. This post is the map of what I built and why; the rest of the series goes deep on each piece.

The itch

I've integrated with OIDC providers plenty of times — configured redirect URIs, validated JWTs, cursed at claim mappings. But integrating with a black box teaches you the client half of the protocol and leaves the server half as folklore. What does the authorization server actually do between /authorize and /token? Where do refresh tokens live? What breaks when you rotate signing keys? I wanted to know by building, not by reading.

What got built

A small but complete OIDC ecosystem, five deployable pieces:

  • provider — an authorization server on Spring Authorization Server: registered clients, users, consent, token issuance, JWKS, an admin UI and admin API, Flyway-managed schema.
  • client — a relying-party web app on Spring Security's OAuth2 client: the classic login dance, server-side sessions, Thymeleaf.
  • resource — an edge gateway that validates JWTs it didn't issue: JWKS resolution, route-level authorization, trusted-header propagation, rate limiting.
  • sample-webapp — a "third-party" RP: what an external developer integrating with my IdP actually experiences — login, consent, calling the gateway with the user's token.
  • sample-m2m — machine-to-machine: client_credentials flow end to end.

Plus the plumbing that makes it feel real: a MySQL-backed compose harness for a prod profile, Kubernetes manifests, and an edge design for a cloud application gateway.

What "production-shaped" means here

A toy IdP is a weekend. A convincing one keeps pulling you deeper. The review backlog on this project reads like a real audit:

  • Session-authenticated admin API needed its own stateless security chain — CSRF-off plus cookies is a hole, not a convenience.
  • sub had to move from username to an immutable UUID — mutable subjects are account-confusion bugs waiting for a re-registered username.
  • client_secret_post had to die — secrets in request bodies end up in access logs.
  • Prod cookies needed secure/same-site set in config, not in a README checklist nobody re-reads.

Every one of those is a "oh, that's why the spec says that" moment — the kind you don't get from the client side.

The series

  1. This post — the architecture and the why.
  2. Spring Authorization Server from zero to first login.
  3. The relying party: Spring Security OAuth2 client, Thymeleaf and React variants.
  4. The edge gateway: validating tokens you didn't issue.
  5. Third parties: client_credentials, consent screens, and scope design.
  6. Operating it: health probes, observability, deploy manifests, and the security review that hurt.

Next up: standing up the provider — what Spring Authorization Server hands you for free, and the surprising amount it doesn't.

Monday, November 30, 2026

jq recipes you'll actually use

Companion cheatsheet with every recipe: jq quick reference — knowledge base entry.

You have JSON from an API, a CLI, a config file — and you need three fields out of it, flattened, without writing a script. That's the jq sweet spot: it reads JSON, applies a small filter language, and prints exactly what you asked for. Below are the patterns I reach for daily.

Reading fields

jq '.field'              # one field
jq '.a.b.c'              # nested
jq '.items[0]'           # first array element
jq '.[]'                 # every element

Shaping output

jq '.[] | {name, id}'                       # object per element
jq -r '.[] | [.id, .name] | @tsv'           # tab-separated rows
jq 'map(.name) | unique | sort'             # dedupe + sort

Filtering

jq '.[] | select(.x > 5)'
jq 'first(.[] | select(.active))'
jq '.[] | select(.name | test("^harbour-"))'

gh api + jq — the power combo

gh api 'orgs/ORG/repos?per_page=100' --jq '.[].name'
gh api repos/ORG/REPO/git/trees/main?recursive=1 --jq '.tree[].path'

--jq on gh api is exactly the same as piping to jq — it just saves a pipe.

Gotchas that bite everyone

  • .foo.bar dies on a null parent — use .foo?.bar or .foo // {}
  • select() filters, map() transforms — mixing them up is the #1 mistake
  • @tsv/@csv need -r or the output looks wrong
  • Piping one jq into another? Stay in JSON mode — only add -r at the end.

The full table of recipes — aggregation, objects, interpolation, conditionals — is in the KB entry.

Saturday, November 28, 2026

Markdown to Word without the template tax

Full writeup with reproducible steps: How to convert Markdown to Word (.docx) without templates — knowledge base entry.

Every so often a runbook, note, or tracking doc written in Markdown needs to reach someone who lives in Word. Pandoc works, but the output usually needs a manual cleanup pass — and corporate recipients just want a native .docx.

I packaged the conversion as a Devin/agent skill: simple-md-docx-converter. Feed it any well-formed .md file and it produces a Word document using native constructs — real headings, tables, code blocks, task lists — powered by python-docx. No template file, no placeholder contract to maintain.

  • Headings, lists (incl. task lists), tables, code fences, blockquotes, strikethrough, horizontal rules
  • <mark> highlighting, inline images, {{toc}} fields, page breaks
  • Multi-file merge into a single document
  • Mermaid diagrams render to images when mmdc/Kroki is available, else degrade to labelled text
  • Optional --template (.docx/.dotx or a named template) to inherit corporate styles and fill {{key}} tokens

Quick start:

git clone https://gitlab.com/shoujunni/skill-md-docx-converter.git
cd skill-md-docx-converter
./scripts/setup.sh
.venv/bin/python scripts/convert_md_to_docx.py input.md

The git workflow trick worth stealing: it degrades gracefully — if Mermaid tooling isn't installed, diagrams become clearly-labelled text instead of failing. Source and tests are on GitLab.

Java, JavaScript, HTML, XHTML, AJAX, CSS, etc.