Migrating to Karni 0.5.0¶
Every change below is recorded in Karni's machine-readable changelog
(packages/karni/karni/changelog/0.5.0.toml). Nothing here breaks a 0.4.0
project's build or tests. karni upgrade adds the URL marker, reports
anything it could not place, and lists the public-read viewsets to review and
the agent files to regenerate. Changing who may write a resource is the
project's decision, so no codemod touches access. karni check may print a
new warning.
Upgrading¶
pipx upgrade karni-cli # the CLI carries the changelog
karni upgrade --dry-run # shows the diff and the notes below, writes nothing
karni upgrade # applies the codemod on a clean git tree
# then pin karni to 0.5.0 in pyproject.toml, reinstall, and run:
karni rules sync # rewrite the agent files
karni check # prints karni.W102 for each viewset to review
karni check --deploy # before going live, with production settings
Changed in 0.5.0¶
Public-read viewsets: review who may write¶
This is a security fix. In 0.4.0, karni make model ... --access public-read
and karni make viewset ... --access public-read wrote this declaration:
A new project also has open self-registration (POST /api/auth/register/).
Together they let anyone who opens an account create, change and delete
every row of the resource through the API. The test karni make test
generated acted as any signed-in user, so it passed and did not catch it.
The problem was found in a real project built on 0.4.0.
From 0.5.0, --access public-read writes:
staff is the system role in the default KARNI_ROLES.
--access public-read:<role> names another role, for example
public-read:editor. karni make test now acts as the role the write
predicate names, so the generated test really creates, updates and deletes.
What to do in a 0.4.0 project:
- Run
karni check. Each viewset whosewritelets every signed-in user change every row is reported as karni.W102. - For each one, decide who may write and change
write. UseHasRole("staff")(what the preset writes now),Granted()(the roles' grants) orOwned("<field>")(rows the user owns). - If a generated test now fails because its user cannot write, pass the
role:
self.assert_crud(VenueViewSet, "staff"), or regenerate it withkarni make test Venue --force.
create=Authenticated() with an owned write (anyone signed in may add a
row, and only its owner may change it) is the normal pattern for content
users create, and W102 does not report it.
Self-registration can be turned off¶
KARNI_ACCOUNTS_REGISTRATION (default True, so nothing changes) decides
whether anyone may open an account. False leaves register/ out of the
URLs, so it answers 404 and is absent from the OpenAPI schema. Use it when
staff create every account, for example a brochure site with a CMS. W102
is silent while registration is off. See
closing registration.
If every signed-in user is trusted to write and W102 is wrong for your
project, add "karni.W102" to SILENCED_SYSTEM_CHECKS.
Public creates are rate-limited¶
A viewset whose create anyone may call (create=Public(), or
write=Public() without a create) now gets three protections without a
line of code:
- A rate limit. Each caller (the user, else the client IP) may create
KARNI_PUBLIC_CREATE_RATErows, default 10 an hour. Over it,createanswers 429 withRetry-After. A 0.4.0 project that wrote its ownget_throttles()for a contact form keeps it: an overriddenget_throttles()or athrottle_classesset on the viewset replaces the default. You can delete that code and rely on the default, or declarethrottle = Throttle(create="30/hour"). - A honeypot. A request that fills the field named by
KARNI_PUBLIC_CREATE_HONEYPOT_FIELD(defaulthomepage) is answered 202 and saves nothing.@karni/ui'sResourceFormrenders it hidden. A model with a field of that name keeps the field and gets no honeypot. - No anonymous imports. The import endpoints of such a viewset need a
signed-in user, who still has to pass
createorwrite. In 0.4.0 an anonymous caller could import a file of rows through a public form.
What to do: if a public endpoint legitimately takes more than 10 creates an
hour from one caller (an integration posting from one server, say), raise
its limit with throttle = Throttle(create="500/hour"), turn it off with
Throttle(create=None), or change KARNI_PUBLIC_CREATE_RATE for every
viewset (None turns the default off). The pytest plugin now starts each
test with empty rate-limit counters, so a suite that posts to a public form
many times keeps passing. See rate limits.
Security headers on every response¶
karni.security.SecurityHeadersMiddleware is now in the MIDDLEWARE that
karni_settings() builds. Every response carries a Content-Security-Policy
and a Permissions-Policy. With DEBUG on the policy is report-only, so
development keeps working and the browser console lists what production
would block. With DEBUG off it is enforced.
The default policy allows what Karni serves: the admin, the browsable API,
the API docs pages, the welcome page and the @karni/ui app. A project page
that loads a script, stylesheet or font from another host (Google Fonts,
analytics, a map), or runs an inline script, is blocked in production until
the policy allows it:
# config/settings.py, after karni_settings(globals())
KARNI_CSP = {
"style-src": ["https://fonts.googleapis.com"],
"font-src": ["https://fonts.gstatic.com"],
}
What to do: open the project's pages with DEBUG on and read the browser
console for Content-Security-Policy-Report-Only reports. Add each host
they name to KARNI_CSP, or allow one view's extra sources with
@csp_extend. If your proxy already sends a policy, set KARNI_CSP = None.
A project that defines MIDDLEWARE itself, after karni_settings(),
does not get the middleware: add "karni.security.SecurityHeadersMiddleware"
after Django's SecurityMiddleware. See
security headers.
Deploy checks¶
karni check --deploy runs Django's and Karni's deploy checks
(karni.W510 to karni.W520) with whatever environment it is given, and
fails on any warning. Run it once with the production environment before the
next release. With the scaffold's development values it reports DEBUG, the
SECRET_KEY, ALLOWED_HOSTS, CSRF_TRUSTED_ORIGINS, HSTS, the cookies,
the admin path, CORS, the content security policy and email, each with its
fix.
CSRF_TRUSTED_ORIGINS is now read from the environment (comma-separated),
and SECURE_HSTS_SECONDS too in the production profile. See
deploy checks.
A marker for project routes in config/urls.py¶
A new project's config/urls.py carries a # karni:urls line inside
urlpatterns, before *welcome_urls():
urlpatterns = [
...,
*media_urls(),
# Project routes that `karni make` wires (a public site's include goes here).
# karni:urls
# Only while DEBUG is on, and only until a route above answers "/".
*welcome_urls(),
]
karni make site <app> inserts path("", include("<app>.urls")) at that
line, so a public site replaces the welcome page, and
karni make view inserts routes at the same marker inside the site app's
own urls.py. The codemod adds the two lines to a config/urls.py that has
*welcome_urls() and no marker. A URLconf without *welcome_urls() is
listed for you: put the # karni:urls line after your own routes, where an
include at "" may go. Without the marker, karni make site stops with the
line to add by hand.
The agent files: run karni rules sync¶
The generated AGENTS.md and the other adapters now say where app screens
and a public site go. Rules K302 and K306 say they are about app screens,
the new rule K309 covers public server-rendered pages, and the new-page
procedure points at it. Until you run karni rules sync, karni rules sync
--check (and make check) reports the files as stale.
karni seed refuses tables that already hold rows¶
karni seed now prints the models it will write to, then refuses with
E617 (karni explain E617) when one of their tables already holds rows. A
seeded row carries no mark, so seed cannot tell its own rows from real
content, and demo rows added on top of content cannot be told apart later.
The user table is left out, so a fresh project with a superuser still seeds
without flags, and --model narrows the check to the tables it seeds.
What to change:
- A script or Makefile target that seeds the same database more than once:
use
karni seed --reset, which wipes the project's tables first. The reference application's end-to-end script already does. - A script that seeds after loading or creating rows on purpose: add
--force. karni.seeding.seed()does not refuse. Callkarni.seeding.occupied(seed_plan())first if your code wants the same rule.
Real content (a site's copy and images) belongs in a content file loaded
with the new karni load, which is safe to run on
every deploy.
Settings the call reads fail loudly below it¶
karni_settings(globals()) reads nine settings during the call to compute
others: KARNI_AUTH_MODE, KARNI_2FA, KARNI_SOCIAL_AUTH and
KARNI_SOCIAL_PROVIDERS decide INSTALLED_APPS and MIDDLEWARE,
KARNI_FRONTEND_URL feeds CSRF_TRUSTED_ORIGINS, KARNI_AUTH_THROTTLE_RATES
the throttle rates, KARNI_JSON_LOGS builds LOGGING, KARNI_CACHE builds
CACHES and KARNI_STORAGE builds STORAGES. In 0.4.0 one of them
assigned below the call was accepted and changed nothing, so a project could
run with KARNI_AUTH_MODE = "session" in its settings and JWT wiring. From
0.5.0 startup fails with karni.E508, which names the
setting and what was computed from it.
What to do: move the assignment above the karni_settings(globals()) line,
pass it as a keyword (karni_settings(globals(), KARNI_AUTH_MODE="session"))
or set its variable in .env. The list is in
settings, and KARNI_CACHE and
KARNI_STORAGE defined above the call now build CACHES and STORAGES as
the environment variables do. Every other setting works below the call.
The admin logo works wherever it is assigned, and on the login screen¶
KARNI_ADMIN_LOGO was read during the call, so a value assigned below it was
ignored without a word. The admin now reads it on every request:
UNFOLD["SITE_LOGO"] and UNFOLD["SITE_ICON"] hold
karni.conf.admin_logo.site_logo and site_icon, which unfold calls with
the request. The login screen shows the same logo above its title through
karni_admin/login.html, which karni.admin sets as the admin site's
login_template unless the site has one.
What to do: nothing for a project that sets the logo above the call or in
.env. A project that replaces UNFOLD below the call (UNFOLD = {...})
while KARNI_ADMIN_LOGO is set now fails with karni.E508: change UNFOLD
in place, or add the two entries to yours. A site with its own
login_template keeps it. unfold_logo_entries() still exists for a project
that builds UNFOLD itself.
karni make model adds the images extra to pyproject.toml¶
An ImageField needs Pillow, which the karni[images] extra installs. In
0.4.0 karni make model ... photo:image printed a note. It now changes the
karni requirement in [project].dependencies to karni[images], keeping
its version spec, markers and other extras (karni[s3]>=0.4 becomes
karni[s3,images]>=0.4), prints the change, and says to reinstall
(pip install -e ., or docker compose build). Only that one string
changes, --dry-run shows it in the diff, and a project that lists the extra
already is left alone. When karni is not a direct dependency the note
names the step instead.
One dev port: KARNI_DEV_PORT¶
KARNI_DEV_PORT in .env (default 8000) is the port karni serve --local
runs Django on, the port the scaffold's frontend/vite.config.ts proxies
/api and /health to, and the port docker-compose.yml publishes Django
on. The config reads it from ../.env or the environment with Vite's
loadEnv. KARNI_API_PROXY still wins when it is set, which is how the
compose stack points the frontend container at django:8000.
A 0.4.0 project's vite.config.ts keeps working: it proxies to port 8000,
and karni serve --local prints the KARNI_API_PROXY=... npm run dev line
whenever the server and the proxy disagree. To adopt the setting, replace
the const target = ... line and the defineConfig({...}) call with the
scaffold's defineConfig(({ mode }) => {...}) form (a fresh karni new
shows it), add the commented KARNI_DEV_PORT line to .env.example, and
publish "${KARNI_DEV_PORT:-8000}:8000" in docker-compose.yml.
A site app's runtime is the karni-site module¶
karni make site now installs the karni-site module the way karni add
site does (the dependency in pyproject.toml, karni_site in the
# karni:apps block, its redirect middleware in the # karni:middleware
block and its site context processor), sets handler404 and
handler500 in config/urls.py to its error views, and writes
templates/500.html. The module brings the {% ifactive %} tag for the
current menu item, the {% csp_hash %} and {% csp_allow %} tags for a
design's inline scripts and other origins under the
Content-Security-Policy, the error views that render the site's own pages
with the request, and everything the client edits in the admin (blocks,
menus, the site's details, redirects, page titles). It has tables, so run
karni migrate after installing it.
A site app created with an earlier 0.5.0 build keeps working. To get the missing pieces, install the module and let the generator add what is not there:
pip install karni-site # or add it to pyproject.toml and rebuild
karni make site <app> --force
karni add site # records the module's agent guidance
karni migrate
--force creates only the missing files (templates/500.html) and adds
the wiring. Existing files are kept. Then load the tags where you want
them: {% load static karni_site %} at the top of base.html, and
{% ifactive "<app>:<name>" %} around the class or attribute each menu
link uses for the current page. The karni-site README
has the details.
The staff app requires sign-in and opens on a dashboard¶
A project scaffolded by karni new 0.5.0 has a frontend/src/layout.tsx
that wraps every page but a sign-in page in <AuthGuard explain> (a visitor
who is not signed in sees the sign-in prompt in place), builds its menu with
@karni/ui's routeNavItems and offers "Sign out", and a
frontend/src/pages/home.tsx that renders <Dashboard>: the counts and
newest rows of every model that declares class Karni: dashboard = {...}
(API: the staff dashboard).
A project scaffolded earlier keeps its own two files, which still work. To
adopt the new ones, scaffold a throwaway project (karni new tmp) and copy
frontend/src/layout.tsx and frontend/src/pages/home.tsx over yours
(frontend/src/api/health.ts is no longer needed), then give the models
that belong on the home page a dashboard declaration.
The admin wears the project's karni-theme.css¶
karni_settings() now sets KARNI_THEME_CSS to
frontend/src/karni-theme.css and serves that file to the admin as
karni/project-theme.css, loaded third in UNFOLD["STYLES"]
(theming).
What to change:
- A project that appended a stylesheet of
--karni-*overrides toUNFOLD["STYLES"]for the admin can drop it, if the frontend'skarni-theme.cssholds the same values. - A project that defines
STATICFILES_FINDERSitself adds"karni.admin.theme.ProjectThemeFinder"to it, or the admin's<link>answers 404.KARNI_THEME_CSS = ""turns the project theme off instead. - A
karni-theme.cssthat references the frontend's own variables (a shadcn/ui project) has no effect in the admin, which does not define them.karni ui detect --csswrites literal values.
karni-theme.css keeps dark mode¶
karni ui detect now writes a light-only colour under :root:not(.dark).
In 0.4.0 it wrote :root, which has the same specificity as @karni/ui's
.dark block and comes later, so the light colours also applied in dark
mode. A karni-theme.css written by 0.4.0 keeps that behaviour until it is
regenerated: run karni ui detect --force (the same sources, the new
blocks), or change its :root { colour block to :root:not(.dark) { by
hand.
A production stack: karni make deploy compose¶
A new project gets docker-compose.prod.yml, a Caddyfile that a service
finally runs, and .env.prod.example: a one-shot release service, django
under gunicorn with uvicorn workers, Celery worker and beat, caddy with
automatic TLS, db, redis and a backup service, with health checks,
restart policies and named volumes. Every container from the production
image runs karni check --deploy first and refuses to start while it fails
(E520). Deploying to a server is the walk-through.
A 0.4.0 project keeps working as it is. To adopt the stack:
- Copy the
staff-appandbackupstages and theprodstage'sCOPY --from=staff-appline andENTRYPOINTfrom a fresh project'sDockerfile(karni newin a scratch folder). - Add the
basepathline tofrontend/src/routes.tsx(next section). - Run
karni make deploy compose --force. It replaces theCaddyfileand adds.env.prodto.gitignoreand.dockerignore. It stops withC105when theDockerfilestill lacks a target it needs.
KARNI_HEALTH_CHECKS is now read from the environment (comma-separated), so a
deployment without a Celery worker leaves the Celery check out in .env.prod.
The staff app follows Vite's base path¶
The production stack serves the staff app under /app/, so the build uses
that path as Vite's base, and the router has to know it. The scaffold's
frontend/src/routes.tsx now creates the router with it:
export const router = createRouter({
routeTree: root.addChildren(routes),
basepath: import.meta.env.BASE_URL,
});
In development the base is /, so nothing changes there. Add the line to a
0.4.0 project before serving its staff app under a path.
The agent files name karni make form¶
Rule K309 and the new-model procedure now tell an agent that a public
form is karni make form <name> <field:type> ... [--notify SETTING] plus
{% karni_form "<name>" %} in the page, and never a hand-written form view,
throttle or form script. Run karni rules sync. Until you do, karni rules
sync --check reports the files as stale.
A form a project wrote by hand keeps working. To move one to the generated
form, keep its model and viewset (a viewset with create=Public() needs no
throttle of its own since this release), put {% load karni_site %} and
{% karni_form "<model name>" %} where the page's <form> was, include
karni_site.urls in config/urls.py (path("", include("karni_site.urls"))
before the site's own include), and delete the form's script. For the
email, call karni_site.notify.notify_recipients from the listener. See
public forms.
A procedure from a design to content: run karni rules sync¶
The new site-from-design procedure (karni rules --procedure
site-from-design) gives an agent the steps from a designer's pages to a
site with real content: karni import design, karni design analyze (the
models the repeated content needs, and the decisions the markup cannot
settle), the karni make model commands, karni design extract, karni
load and templates that loop over the rows. See From a design to
content. Run karni rules sync to add its slash
command files. Until then karni rules sync --check (and make check)
reports the files as stale.
The admin is light only¶
The admin used to follow the system's light or dark preference, with a switch in the sidebar. It now shows the light palette on every page and the login screen, with no switch, and a browser in dark mode still gets the light admin. There is no setting for it.
What to do: nothing. A project that wants the switch or the dark palette sets
UNFOLD["THEME"] itself (None for the switch, "dark" for dark) and its
value wins. See admin theming.
The admin is simple to use¶
Every admin now has labelled Add, Edit, Delete and Restore buttons, bulk actions (including a new Edit selected), a fixed bar of save buttons, a collapsed Details section for ids and timestamps, at most six list columns (the name first, the updated time last), an empty state, and a Getting started panel on the home page. See the screens.
What to do: run python manage.py migrate. The panel's per-user dismissal is
one new table, karni_admin_guidedismissal, from karni.admin's first
migration. Nothing else needs to change. To keep the old look of one model, set
karni_row_actions = False or karni_details = False on its admin (through
AdminMeta.extra), and KARNI_ADMIN_GUIDE = False removes the panel. A project
with its own UNFOLD["ACCOUNT"]["navigation"] list keeps it and loses only the
user menu entry that brings the panel back. A project's own change_list_template
or change_form_template wins over Karni's.
Sign-in with an ID token (experimental)¶
Nothing to change. 0.4.1 adds sign-in with a Google, Microsoft or Apple ID
token (accounts).
It is off until KARNI_SOCIAL_TOKEN_PROVIDERS names a provider, and it needs
pip install 'karni[social-token]'. The release brings one migration,
karni_accounts.0006_social_identity, which creates the empty
SocialIdentity table: karni migrate applies it like any other. The new
names are experimental: a later minor
release may change them, and says so here.
Sign-in with a code sent by email (experimental)¶
Nothing to change. 0.4.1 adds sign-in with a code sent by email
(accounts). It is off
until KARNI_EMAIL_OTP = True. The release brings one migration,
karni_accounts.0007_login_code, which creates the empty LoginCode table:
karni migrate applies it like any other. The new names are
experimental: a later minor release may
change them, and says so here.
Projects have a kind¶
karni new asks what kind of project it is, or takes --kind: site (a
public website the client edits in the admin), app (an API and a React
app, what karni new always made) or site+app. It records the answer in
pyproject.toml:
karni context prints it on its first line and the agent files state it
with its stack. A project made before this has no kind, and Karni reads
the kind its files show: karni_site in the # karni:apps block makes a
site (a site+app with a frontend/), anything else an app. Add the line to
say it yourself. A value Karni does not know fails karni context and
karni rules sync with C112.
An app that gets a public website runs karni add site. It wires karni-site
as before and sets kind = "site+app", then karni make site website or
karni import design makes the site app. karni make site and karni
import design set the kind the same way when they wire the module. To go
back, set kind = "app" again and run karni rules sync. The site's files
stay until you delete them: the site app and its include in
config/urls.py, karni-site in pyproject.toml, and karni_site with its
middleware and context processor in config/settings.py. See
start a site project.
The agent files state the kind: run karni rules sync¶
AGENTS.md and the other adapters open with the project's kind and its stack,
so an agent never asks which technology to use. The site-from-design
procedure is the whole flow now: karni design analyze first, then karni
import design --editable --map content/design-map.json (the content the map
reads into rows gets no blocks, because the loops render it from the rows),
the models, the content, the loops, karni make form for each <form>, the
page test and karni check. Run karni rules sync. Until then karni rules
sync --check (and make check) reports the files as stale.
A site imported before with --editable and no map keeps its blocks. Where
a template now loops over rows, take the {% editable %} tags out of the
markup inside the loop, or import again with --map before you edit the
templates.
Search engines: {% karni_seo %}, sitemap.xml and robots.txt¶
A site app's base.html now has {% karni_seo %} in its head, around the
title and description:
{% karni_seo %}<title>{% block title %}{{ site.name }}{% endblock %}</title>
<meta name="description" content="{% block description %}{% endblock %}">{% block seo %}{% endblock %}{% endkarni_seo %}
It writes the canonical link, the share tags and the site's JSON-LD, so
remove the <link rel="canonical"> an earlier base.html had. And
config/urls.py includes karni_site's URLs before the site's own:
which answer /robots.txt (closed to crawlers unless DJANGO_ENV is
prod, or KARNI_SITE_ALLOW_INDEXING says otherwise) and /sitemap.xml.
karni add site adds the include to an existing project, and so does
karni make site <app> --force. Then karni check --seo renders every
page and reports what search engines would find missing. Install the
module's images extra for the smaller copies of uploaded images:
pip install "karni-site[images]".
The design's images are sized¶
karni import design now writes width and height on the design's
<img> tags that lack them, from each image's own file, and marks them
data-karni-image, which {% karni_seo %}'s CSS keeps in proportion
(height: auto). Where Pillow is installed it also writes smaller WebP
copies of each large JPEG, PNG or WebP next to it under static/<app>/
(hero.jpg.640w.webp) and a srcset and sizes that use them. The next
import of a design changes the templates the project has not edited since
the last one, and keeps the edited ones as before. Without Pillow
(pip install pillow where karni runs) only the sizes are written.
Grants open admin pages¶
In 0.4.0 a staff user opened a model's admin page only with Django's model
permission for it, and the role groups karni sync-roles creates carry
none. A staff user with the staff role, which grants everything, got a 403
on the project's own models. Now a role's grant (app.model:<action>) opens
the page for that action, inside the grant's scope and unless a veto refuses
it. Django's model permissions still open pages for a user without a grant,
superusers open everything, and the admin index lists exactly the models
the user may open.
This widens who can open admin pages. Before you upgrade:
- List who has staff status (
is_staff) and which roles each person holds. Every staff user with thestaffrole now opens every Karni admin page, users and roles included. - A grant on the user model lets its holder change accounts and give
roles. Only a superuser changes
is_superuseroruser_permissions, or edits or deletes a superuser's account. - Signing in still needs
is_staff. A role alone gives no admin access.
To keep the 0.4.0 rule (Django's model permissions open pages, the grants
decide the rows), set it after karni_settings(), or in .env:
karni_site.admin.GrantedAdminMixin and GrantedInlineMixin, which did the
same for the site module's own pages, are gone: every Karni admin has the
behaviour, and karni.admin.KarniInlineMixin gives it to an inline of your
own. See who may open a page.
Tests run on an empty local-memory cache¶
In 0.4.0 a project's tests used the project's own cache, Redis at
REDIS_URL, the one the development server uses. Throttle counters, a
listener's "already queued" flag and anything else a test cached stayed
there for the next test, the next run and the dev server, so tests failed
at random. Now Karni's pytest plugin gives every test an empty
local-memory cache for each alias in CACHES, and the tests of a new
project never connect to Redis.
A test that relied on a value an earlier test cached now finds the cache empty: set the value up in the test or a fixture. A test that needs Redis itself keeps the project's cache:
karni_test_cache = project under [tool.pytest.ini_options] keeps the
project's cache for every test, as in 0.4.0. A conftest.py fixture that
swapped CACHES for a local-memory cache can go. See
the cache in tests.
Files under the project in development¶
In 0.4.0 MEDIA_ROOT and STATIC_ROOT defaulted to /data/media and
/data/static in every profile, and .env.example set them too. That
folder exists only in the container, so a project run on the host
(karni serve --local) could not store an upload. Now the dev profile
stores them under the project: data/media and data/static next to
manage.py, which .gitignore already leaves out. A relative value, in
.env or from the default, is read from the project root (BASE_DIR, else
the folder above config/), whatever folder a command runs from. The prod
profile keeps /data/media and /data/static.
A project made with 0.4.0 keeps working as it is: its .env sets
/data/media. To get the new default on the host, give the containers the
/data paths first, in the Dockerfile's base and prod stages:
and then remove MEDIA_ROOT and STATIC_ROOT from .env (or set them to
data/media and data/static). karni make deploy compose already writes
the /data paths into .env.prod.
The frontend moves to Zod 4¶
npm install in a 0.4.0 project's frontend/ reports two high-severity
findings: Zod before 4.6.6 can exhaust memory validating an oversized
collection (GHSA-mrhx-c7xc-m3w5),
and @karni/ui depends on it. A new project's frontend/package.json now
has:
@karni/ui 0.5.0 accepts Zod 3 (3.23 or later) and Zod 4 (4.6.6 or later),
with @hookform/resolvers 3 or 5, so an earlier project keeps working
without a change. To clear the audit, set the three lines above in
frontend/package.json and run (cd frontend && npm install).
Code of your own that builds Zod schemas may need changes first: Zod 4
drops required_error and invalid_type_error (pass { message } or
{ error }), and reads a failure's issues rather than errors. Zod's
own migration guide lists the rest. Then run npm run build and karni
check in the project.
minimatch is overridden in the frontend¶
npm audit in frontend/ reports minimatch 7.0.0 to 11.0.0 as moderate:
glob parts can make a match take very long
(GHSA-g3hv-75wg-m249).
typescript-eslint, which ESLint loads to lint .ts and .tsx files, still
asks for minimatch 10, so no update clears it. A new project's
frontend/package.json overrides those versions alone:
ESLint's own minimatch 3, which the advisory does not cover, stays as it is.
In an earlier project, add the block to frontend/package.json, run
(cd frontend && npm install), then npm run lint and
karni check. Take the block out once typescript-eslint moves to
minimatch 11.
Production email: EMAIL_URL and karni.W520¶
karni_settings() reads the mail server from EMAIL_URL
(smtp+tls://user:password@smtp.example.com:587, smtps:// for SSL), and
DEFAULT_FROM_EMAIL and SERVER_EMAIL from the environment. A project that
sets none of them keeps Django's defaults, and development still prints mail
to the console unless EMAIL_URL names a server. A project that assigns the
EMAIL_* settings in config/settings.py keeps its own values.
karni check --deploy, which the production containers run before they
start, now reports karni.W520 while production email goes nowhere: the
console, locmem, dummy or file backend, or a sender at localhost (Django's
webmaster@localhost). Before the next deploy, add the two lines to
.env.prod:
A project that sends no email adds the code to config/settings.py instead:
SILENCED_SYSTEM_CHECKS += ["karni.W520"]. A new project's
.env.prod.example lists the email settings, commented out.
The development worker: threads on a Mac, and a broker timeout¶
karni worker on a Mac now runs Celery's threads pool. It ran solo in
0.4.0, which runs one task at a time and stops answering celery inspect
and the health check's ping while a task runs. Celery's default prefork
pool fails every task on macOS: billiard 4.3 starts its processes with
spawn there, and Celery rebuilds its task state in a spawned process only
on Windows. --pool (or -P) picks another pool, for example
karni worker --pool solo. On Linux and in Docker, Celery's prefork stays
the default.
The dev profile now sets CELERY_BROKER_TRANSPORT_OPTIONS = {"socket_timeout": 5}.
At a warm shutdown, Celery's Redis transport reads the answer to the worker's
last BRPOP without a timeout. A Redis that never sends it, such as a
long-running Redis on a Mac whose timers stalled, kept the worker in "Warm
shutdown" until it was killed. With the timeout the worker exits within about
six seconds. The prod profile keeps Celery's default. A project that sets
CELERY_BROKER_TRANSPORT_OPTIONS itself keeps its own value: add
"socket_timeout": 5 to it for the same bound in development.
Menus that list a model's rows¶
A menu item with children from a model and neither a title nor an address now lists the model's rows in its own place: a footer that lists every service is one such item. In 0.4.0 the same item rendered as an entry with an empty link and the rows as its children. Give the item a title, or an address, to keep the old shape.
karni import design --editable --map seeds a list whose links are exactly
one model's detail pages (every one, once, by its title) as that model's
rows: the seed template marks the list with
data-karni-children-from="<app>.<Model>", and the import's report names
each menu. A menu the database already has keeps its items: delete it in the
admin to have it seeded again from the new template.
The primary key is no longer a derived filter¶
The filterset KarniFilterBackend derives for a BaseViewSet no longer
filters on the model's own primary key, whatever its type. With
integer keys ?id__gte= would let a
client page through the table by key. Models with an integer key (an
AutoField) used to get all three. A project whose clients send ?id=,
?id__gte= or ?id__lte= declares them:
class ReadingViewSet(BaseViewSet):
model = Reading
access = Access(read=HasRole("analyst"), write=HasRole("analyst"))
filterset_fields = {"id": ["exact", "gte", "lte"]}
A relation to an integer-keyed model now filters with
karni.api.filters.IntegerFilter, so ?reading=1.5 is a 400 instead of
matching row 1.
Imports match ids only when asked¶
An upload used to match a row to an existing one by its id column whenever
the model had no natural key, so a file exported from staging could update
unrelated rows with the same ids in production. Now the id column matches
only with the import's match_ids option (the preview body's
"match_ids": true, or the admin's map step), and keep_ids creates rows
with the file's ids for legacy data (import and export).
A relation cell names a target that has a natural key by that key alone,
never also by its id: to let a column carry ids, declare
import_lookup = {"<field>": "id"}. The refusal for a row outside your scope
now reads "not found or not in your scope" whether the row exists or not.
The release brings one migration, karni_transfer.0002_importjob_id_options,
which adds the two options to ImportJob: karni migrate applies it.
Integer keys (experimental)¶
Nothing to change. BigIntBaseModel puts a model on a 64-bit integer key
(choosing the key type), chosen per
model. Karni's own models and the modules keep their UUIDs, so no Karni
migration changes. karni check warns with karni.W530 for a resource on
integer keys that anyone may read. The new names are
experimental: a later minor release
may change them, and says so here.
A procedure from one line to an app: run karni rules sync¶
A new procedure, new-app, takes an agent from a one-line request to a
running app through karni.yaml: a recipe or the blank start (karni
recipes list --match), the questions of karni plan --questions, karni
spec answer, karni plan and karni build, then only the domain logic
that is left (the /new-app flow).
Rule K311 says never to hand-write what karni.yaml can express. Run karni
rules sync for the new-app procedure in AGENTS.md.
Until then karni rules sync --check (and make check) reports the files as
stale. The procedure, the rule, karni recipes and the MCP tools of the flow
are experimental.
Tree models (experimental)¶
A hierarchy is one declaration now: class Region(TreeModel, BaseModel)
(tree models). karni check has a new rule,
hand-written-tree: a project model with a parent (or parent_*)
foreign key to the model itself that is not a TreeModel fails it. Either
make the model a tree, or keep the field and opt out with the reason:
class Folder(TreeModel, BaseModel): # drop the model's own parent field
name = models.CharField(max_length=100)
# karni: allow(hand-written-tree): the parent column belongs to an imported table
class Folder(BaseModel):
parent = models.ForeignKey("self", null=True, on_delete=models.CASCADE)
A field named parent keeps its column (parent_id) and its rows, so
karni migrate changes only what differs: on_delete=PROTECT and the
reverse name children. The new names are
experimental: a later minor release
may change them, and says so here.
The tree scope (experimental)¶
Nothing to change. 0.5.0 adds the tree:<path> scope: a grant on a node of
a tree reaches every row under it (the tree scope).
It applies only where a role grant or a user grant names it. The release
brings one migration, karni_accounts.0010_tree_scope, which adds tree to
the choices of a role grant's scope and changes two help texts, with no
column change: karni migrate applies it like any other. The new names are
Navigation from data (experimental)¶
Nothing to change. A menu from data is opt-in: set KARNI_NAVIGATION to a
list of items, or to "db" with karni.navigation in INSTALLED_APPS
(navigation from data). Only the database source brings
a table, karni_navigation.0001_initial, which karni migrate applies. A
project's layout.tsx keeps its menu from the routes until it passes
navSource="server" to Layout. The new names are
experimental: a later minor release
may change them, and says so here.
Response caching is stable¶
Response caching moves to the stable tier.
While KARNI_API_CACHE is off nothing changes. While it is on:
- The header. Every cacheable response carries
X-Cache: HIT,MISSorBYPASS.X-Karni-Cache: hit|missis still sent next to it until 1.0, where it goes, and the first one a process sends raises aKarniDeprecationWarning. ReadX-Cachein your tests and tools (the values are upper case), then setKARNI_API_CACHE_LEGACY_HEADER = Falseto stop sending the old header and the warning. - Who shares an entry. Callers with the same roles now share an entry
when the viewset's read access depends on roles alone (
Public,Authenticated,HasRole, grants scopedall). It was always per user. A response that renders something per user that Karni cannot see, such as a method field readingrequest.useron a serializer Karni did not write for this viewset's own read rule, needsget_cache_scopeon the viewset (a hand-written serializer with aSerializerMethodFieldis already per user). - More writes invalidate.
update(),delete(),bulk_create()andbulk_update()of Karni's querysets, imports and the admin's bulk actions now invalidate for you, once per call. Theinvalidate(Model)calls you wrote after them still work and can go.invalidate(Model)without a key now covers every detail of the model too, not only its lists. - External models.
karni checkrefuses a cached viewset that reads an external or unmanaged model, or one on another database (karni.E410). Declarecache = Cache(ttl=...)orcache = Uncached(reason=...)on it. - Tests. The pytest plugin empties the response cache before each test.
The scheduled flush (KARNI_API_CACHE_FLUSH) and the admin's API cache
screen are new and off until used.
A raw <details> fails karni/no-raw-elements¶
The rule now flags a raw <details> element too: compose Accordion from
@karni/ui (the WAI-ARIA accordion pattern, with keyboard and screen-reader
support), or keep the element with
// eslint-disable-next-line karni/no-raw-elements -- <reason>. A raw
<table> is still flagged, and the message now names DataTable (rows the
page computed) and ComparisonTable next to ResourceTable.
karni rules --check reports the same.
Headings follow the page's outline¶
A page has one <h1>, and the components under it now start at <h2> so no
level is skipped (the axe rule heading-order). EmptyState's title and
FacetPanel's heading are an <h2> (they were <h3>). ResourceDetail takes
headingLevel (default 2) for its title, and its field groups and Record block
sit one level under a title that shows, or at that level when there is none.
EmptyState and FacetPanel take headingLevel too, for a component that
sits deeper. TermsGate replaces the whole app, so its panel is now the
page's <main> with an <h1>: a gate placed inside a page that has its own
<main> passes page={false}. A test that finds one of these by heading level
needs the new level.
The export button's name is its visible text¶
ResourceTable's export buttons are named Export CSV and Export XLSX, the
text people read (WCAG 2.5.3, label in name). They were Export as CSV through
an aria-label. A test or script that finds the button by the old name needs
the new one.
ResourceTable follows the API's page size¶
ResourceTable used to send page_size=25 on every list request, so
KARNI_PAGE_SIZE changed nothing in the screens. It now sends no page_size
until the user picks one from the size menu or the page passes pageSize, so
the API's own size applies (50 by default) and the table reads it from the
first full page. Pass pageSize={25} to keep 25 rows a page. A test that
expects page_size=25 on the first request needs it.
Page blocks (experimental)¶
Nothing to change. @karni/ui adds DashboardGrid, ChartCard, DataTable,
ComparisonTable, Accordion, MarkdownView, useResourceCounts and
ResourceDetail's related tabs (page blocks),
and marked and DOMPurify become dependencies of the package (MarkdownView
loads them on first use). A project that installs @karni/ui from a local
checkout (file:) refreshes its copy: rm -rf node_modules/@karni/ui && npm
install. The OpenAPI schema gains x-karni-related on list operations: accept
the snapshot with KARNI_UPDATE_SNAPSHOTS=1 karni test and commit it. The new
names are experimental.
Impersonation allows one open session per actor¶
start/ now refuses a second session while the actor has one open (IMP004),
and a unique constraint on the open sessions keeps two concurrent starts from
both succeeding. Run karni migrate: migration 0002 ends any older duplicate
open sessions (reason swept) before it adds the constraint. A client that
started a new session without stopping the first now stops it first.
seed --reset wipes the models a seeder names¶
karni seed --reset deleted the rows of the project's own models only. It now
also deletes the rows of every model that has a seeder in an installed app's
seeds.py, whatever app the model belongs to: a module's table (a saved
chart) or UserGrant. The user model is still never deleted. A seeder that
cleaned up after itself (UserGrant.objects.filter(reason=...).delete() at the
top of seed()) can drop that line. If a model holds rows you want to keep,
give it no seeder.
System check warnings print as one line¶
karni migrate, karni seed, karni serve and the other project commands
print the system check warnings as System check identified 5 warnings
(karni.W101, karni.W965 x3).karni checklists them in full. in place of
every paragraph. karni check and manage.py check still print them in full,
and KARNI_SYSTEM_CHECK_OUTPUT=full in the environment restores the full text
for every command. Nothing to change.
A new superuser holds the routed roles¶
karni createsuperuser (and User.objects.create_superuser) now gives the
account every role the routed viewsets' access declarations name, the same
roles karni seed gives the demo account. Before, the first admin was refused
by every public-read, staff and role: viewset with
requires HasRole('staff'), although karni why said a superuser holds every
grant. A superuser created earlier keeps what it has. Give it the roles once:
from karni.accounts.permissions import assign_role, routed_roles
for name in routed_roles():
assign_role(user, name)
To give new superusers another list, subclass KarniUserManager, override
superuser_roles (return [] for none) and bind it as objects on your
user model.
Ignore the egg-info folder¶
pip install -e . writes <project>.egg-info/ in the project root. New
projects ignore it. Add this line to the .gitignore of an older project, or
karni upgrade counts the folder among the dirty files:
New projects start without the legacy cache header¶
A new project's config/settings.py sets
KARNI_API_CACHE_LEGACY_HEADER = env.bool("KARNI_API_CACHE_LEGACY_HEADER", default=False)
below the karni_settings() call, so only X-Cache is sent and the first run
has no deprecation warning. An existing project keeps the default True and its
warning. To drop both, add the same line, once nothing reads X-Karni-Cache.
Admin lists page, filter and sort like a data table¶
Every admin list now shows 25 rows a page, not Django's 100, with a bar at the
bottom: Showing 1 to 25 of 312 notes, previous and next, page numbers, and a
choice of 25, 50 or 100 rows kept in the URL (?per_page=50). Set the default
with KARNI_ADMIN_PER_PAGE, one model's with AdminMeta.per_page (or
list_per_page on an admin class), and the offered sizes with
karni_per_page_choices. On PostgreSQL a table above
KARNI_ADMIN_COUNT_ESTIMATE_ABOVE rows (100000, 0 counts always) shows an
estimate ("about 1,200,000 notes") instead of counting on every page.
A list with no ordering is newest updated first, then newest created, then
newest key. A model without its own verbose_name_plural shows a correct plural
(Categories, Entries) in the admin, with no change to Meta and no migration.
Nothing needs changing, except a project that wants Django's 100 rows
(KARNI_ADMIN_PER_PAGE = 100).
The admin help line comes only from help¶
The one line under an admin page's title is class Karni: help (the spec's
help:) and nothing else. The model docstring is no longer shown, so developer
notes stay out of the admin. Move any docstring line you want people to read
into class Karni: help = "...".
Generated site pages ask for their description¶
karni check --seo reports a page whose description is still the placeholder
karni make site and karni make view write as SITE012 on that page. Write
one sentence about each such page in its {% block description %}, its row's
description, or the admin's Page titles and descriptions. A site with one
such page passed the check before, and two failed it as SITE013.
Index advice covers the project's own models¶
karni.W967 (a field a viewset filters, searches or orders by without an
index) no longer names a module's or Karni's model, whose Meta a project
cannot edit. The modules index their own: karni-approvals adds an index on
PendingChange.action and karni-reports one on GeneratedReport.status, each
in migration 0002_index_filtered_fields. Run karni migrate after upgrading
them. A SILENCED_SYSTEM_CHECKS entry added only for those warnings can go.
karni build writes what Karni's checks ask¶
A spec-built project's next karni build changes two things in
<app>/karni/models.py and writes their migration:
- A required fk of an audited entity (
audit:) or a financial one (a money field, or a decimal named like money) ison_delete=models.PROTECT, notCASCADE(karni.W965). Hard-deleting the row it points at is refused while such rows exist. Soft deletes are unchanged. To cascade on purpose, declare the field again in the project's subclass and give the reason inclass Karni: cascade = {"<field>": "<why>"}. - An entity whose
searchnames its own fields getssearch = SearchField(sources=[...]). The default search provider then matches each word as a prefix through the column's index, instead of scanning the table with a trigram fallback (karni.W967).
Expand nests a tree's parent¶
?expand= now nests every level a path names, also one that comes back to a
model already on the path: ?expand=parent on a tree resource,
?expand=region.parent through a relation, or ?expand=events.venue on a
venue. 0.4.0 answered the key at such a level, though it accepted the path.
A client that read the key there reads parent.id, or leaves the level out
of expand. A parent the requester cannot read expands to null
(expansion).
2FA answers throttled inside the wait¶
After a wrong two-factor code, django-otp refuses every code for 1 second,
then 2, 4, 8 seconds after each further wrong one. 2fa/confirm/,
2fa/disable/ and 2fa/login/ now answer a code sent inside that wait with
429, {"code": "throttled", "retry_after": <seconds>} and a Retry-After
header. 0.4.0 answered 400 invalid_code, so a person who mistyped once and
retyped at once was told the right code was wrong. A replayed ephemeral token
on 2fa/login/ is now 401 replayed_token before the code is checked. If
your 2FA screen handles invalid_code, handle throttled too: say how long
to wait (two-factor auth).
Aggregate labels read the row's name¶
An aggregate grouped by a relation (?group_by=region, ?stack=region__parent)
now labels each group with what people read for the related row: its
Karni.label_field, else its first text field named name, title or
label, else its natural key, which 0.4.0 used. A region keyed by the slug
europe now reads Europe in charts, saved charts and comparisons. The
key of each group is still the row's id, and the response has the same
fields. If your code read the natural key from label (to build a link by
slug, say), read key, or keep the old label with
class Karni: label_field = "slug" on the related model
(aggregations).
Tool-specific agent files are deprecated: keep AGENTS.md¶
AGENTS.md is the one agent file. Coding agents read it, and it now lists the
procedures for routine tasks: a request that starts with /<name>, such as
/new-app a booking app for a yoga studio, asks the agent for that procedure.
karni new no longer writes the files that only one tool reads:
CLAUDE.mdand.claude/commands/.cursor/rules/karni.mdcand.cursor/commands/.windsurf/rules/karni.mdand.windsurf/workflows/.github/copilot-instructions.mdand.github/prompts/.clinerules/karni.md,.junie/AGENTS.mdandCONVENTIONS.md
A project that already has them keeps working. karni rules sync keeps them
up to date through 0.5, and karni rules sync --check still reports them when
they are stale. It also prints one warning, C860, that names them, and
karni doctor mentions them once. They stop being updated, and are removed,
in 1.0. Before then:
- Point your tool at AGENTS.md. Most coding agents read it at the repository root by default. For one that reads only its own file, make that file one line that refers to AGENTS.md, or set the tool to read AGENTS.md.
- Keep project guidance in
karni.rules.py(ADD,OVERRIDE,DISABLE), which feeds AGENTS.md. Nothing you add to a generated file surviveskarni rules sync, so move any such text intokarni.rules.pyfirst. - Delete the files the warning names. A deleted file is not written again. A file of your own (without the generated marker) in one of those places is yours, and Karni leaves it alone.
Run karni rules sync once after upgrading: AGENTS.md gains the procedures
block, so karni rules sync --check (and make check) reports it as stale
until then.
natural_key and import_key are checked at boot¶
karni check (and every manage.py command that runs the system checks)
now fails with karni.E291 when class Karni: natural_key or import_key
is not one field name of the model: a list such as ["name"], or a name
the model does not have. Before, it passed the check and failed every
request that read the model. Write the field name as a string,
natural_key = "name".
The admin soft-deletes rows that PROTECT points at¶
On a soft-delete model the row's Delete page and Delete selected no longer
run Django's hard-delete collector. They soft-delete a row that a PROTECT
foreign key points from, as the API does, and the rows that refer to it stay.
Hard delete selected still refuses it. The row's Delete page is now
karni_admin/delete_confirmation.html: a project-wide
admin/delete_confirmation.html override no longer applies to soft-delete
models, so move it to admin/<app>/<model>/delete_confirmation.html or set
delete_confirmation_template on the admin class.
Wildcard grants skip impersonate, approve and reject (security)¶
Advisory. In karni-impersonation and karni-approvals 0.2.0 through
0.4.0 a wildcard grant reached the module's own actions. Every scaffold declares
user and customer with "*": "own" and staff with "*": "all", so:
- with karni-impersonation, any signed-in user in one of those roles could start an impersonation of another user whose grants are no larger than their own, such as one customer of another, and received that user's tokens.
- with karni-approvals, any member of those roles could approve or reject a pending change to a row they can see (the owner of an invoice could approve a change someone else proposed to it), and was emailed as a checker.
A project whose roles have no wildcard that covers the module's models is not affected. Superusers hold every grant by Karni's convention, as before.
The fix. class Karni: explicit_actions lists the actions only a grant
that names them reaches: "*" and "app.model:*" skip them in KARNI_ROLES,
in a module's roles and in a user grant. The modules mark impersonate,
approve and reject. The next karni migrate (or karni sync-roles with
KARNI_ROLES_AUTOSYNC = False) takes these grants back from the wildcard
roles. A grant set in the permission matrix is kept.
After upgrading:
- Grant the actions by name to the roles that do the job:
KARNI_ROLES = {
**KARNI_ROLES,
"support": {"grants": {"karni_impersonation.impersonationsession:impersonate": "all"}},
"finance": {"grants": {
"karni_approvals.pendingchange:approve": "all",
"karni_approvals.pendingchange:reject": "all",
}},
}
A staff role that used to approve through "*": "all" needs these lines
too.
2. Run karni migrate.
3. Review the impersonation sessions (admin, Karni impersonation) and the
decided pending changes for actors who were not meant to hold the action.
On 0.4.0 or earlier, before you can upgrade, close it in the permission
matrix: for each wildcard role, set impersonate, approve and reject to
nothing and save. The sync keeps a cell the matrix set.
Your own models can use the option too: explicit_actions = ["refund"] next
to actions = ["refund"]. A name that is not one of the model's actions fails
karni check
(E290).
A field argument its type does not take is refused¶
karni make model and karni spec validate refuse a field argument its type
does not take (C104, and C216 in karni.yaml): name:str:200:unique,
body:text:500, price:decimal:10:2:4, venue:fk:Venue:cascade. In 0.4.0
the argument was dropped without a word, so str:200:unique made a
CharField that is not unique.
What to do: remove the argument from scripts and notes that call karni make
model. A model made with such an argument earlier has the field without it:
check that this is what you meant. For a value unique among live rows,
declare it in the model's Meta and make the migration:
from karni.fields import LiveUniqueConstraint
class Company(BaseModel):
name = models.CharField(max_length=200)
class Meta(BaseModel.Meta):
constraints = [LiveUniqueConstraint(fields=["name"])]
email:unique takes :unique as before.