GuidesSecurity and checks
Check architecture with rules¶
Rules are typed promises about your application: "every private action names a
policy", "writes are atomic", "no response leaks password_hash". Each one is a
Python object with a stable ID, deterministic behaviour and an exact fix line.
They are optional, and a project created with hinoki new starts with them on:
# notes/rules.py
"""The project's rules. Weaken them only with the owner's decision (see hinoki-rules.toml)."""
from hinoki import Actions, Schemas, Transactions # add Models with your first model
from hinoki.rules import RuleSet
project_rules = RuleSet(
# Anything not public on purpose names an access policy, and the policy names permissions.
Actions.require_access(match="notes.*", except_=["notes.api.health"]),
Actions.require_permissions(match="notes.*", except_=["notes.api.health"]),
# Responses are concrete Schema types and lists are paginated.
Actions.forbid_model_responses(match="notes.*"),
Actions.require_return_type(match="notes.*"),
Actions.require_pagination(match="notes.*"),
# Writes run in a transaction that rolls back before errors become HTTP.
Transactions.require_atomic(),
# Secrets never reach a client, and request text is bounded.
Schemas.forbid_exposure("password_hash", "password", "token"),
Schemas.require_string_limits(),
# Turn these on with your first model (a model rule that matches no model
# fails the check): tables are pinned and foreign keys are indexed.
# Models.require_explicit_table(match="notes.*"),
# Models.require_foreign_key_index(match="notes.*"),
)
notes/main.py passes the set to the application with rules=project_rules.
Check it at any time:
hinoki check
The eleven rules¶
| ID | Rule | Phase | Checks |
|---|---|---|---|
HNK-ACC-001 |
Actions.require_access(match="*", except_=()) |
startup | every matching action names an Access policy (public by default is the common hole) |
HNK-ACC-002 |
Actions.require_permissions(match="*", except_=()) |
startup | an action with an Access policy names at least one permission, so "any authenticated caller" is never implicit |
HNK-API-001 |
Actions.forbid_model_responses(match="*", except_=()) |
startup | no action returns a Model (or a list or page of them): responses are Schema classes |
HNK-API-002 |
Actions.require_return_type(match="*", except_=()) |
startup | every action annotates a concrete return type (not missing, Any or object; None is fine for a 204) |
HNK-API-003 |
Actions.require_pagination(match="*", except_=()) |
startup | a GET action never returns a plain list[...] (alone or in a union): it returns a Page |
HNK-TXN-001 |
Transactions.require_atomic(methods=("POST", "PUT", "PATCH", "DELETE"), match="*", except_=()) |
startup | state-changing actions declare atomic=True, on the action or its RouteGroup |
HNK-SCH-001 |
Schemas.forbid_exposure(*fields) |
startup | the named fields never appear in a response Schema: nested, in a subclass, in a union variant, as a field, an alias or a computed field |
HNK-SCH-002 |
Schemas.require_string_limits() |
startup | every text field a client sends (nested, in containers, dict values and union variants included) has max_length or one_of; Enum and Literal fields pass |
HNK-DB-001 |
Models.require_explicit_table(match="*") |
startup | matching models pin their table with @db.table(...) or table=, so renaming the class cannot rename the table |
HNK-DB-002 |
Models.require_foreign_key_index(match="*") |
startup | every foreign-key column leads an index, a primary key or a unique constraint |
HNK-IMP-001 |
Imports.forbid(source, target) |
static | modules under source never import target, read from the source files; dynamic imports are reported, not ignored |
Every built-in rule has severity error. HNK-API-002 matters most for actions
with validate_response=False: any other action with an unusable return
annotation already stops the app. HNK-TXN-001 does not check the admin's own
routes, which open their own short transactions.
Choose what a rule covers¶
Action rules match fnmatch patterns against an action's qualified name:
module.function for a function, module.Class.method for an API class (named
after the class it is mounted on), and module.<Model>Crud.<action> for a
crud(...) value, where module is the one that calls crud(...). A bare health matches nothing; write
notes.api.health or *.health. except_ takes the same patterns and is how
you say "public on purpose". The Blog example names its exceptions once:
# blog/rules.py
PUBLIC = [
"blog.api.health",
"blog.api.Posts.listing",
"blog.api.Posts.one",
"blog.accounts.*.login", # public on purpose: it is how you sign in
]
SIGNED_IN = ["blog.accounts.*.me"] # any signed-in user, no permission
blog_rules = RuleSet(
Actions.require_access(match="blog.*", except_=PUBLIC),
Actions.require_permissions(match="blog.*", except_=[*PUBLIC, *SIGNED_IN]),
Transactions.require_atomic(except_=["blog.accounts.*.login"]),
Schemas.forbid_exposure("token", "password_hash"),
Imports.forbid(source="blog.models", target="blog.api"),
# ... and the other six rules, see examples/blog/rules.py
)
The model rules match the model's module (blog.*) and report unverifiable
when no model matches, even with *. require_access and require_atomic
report unverifiable when a pattern other than * matches no action. Neither
passes silently.
When rules run¶
| Where | Rules | Waivers | On failure |
|---|---|---|---|
Application startup (hinoki dev, hinoki serve, any ASGI server, the test clients) |
startup rules of rules= |
the waiver file | startup fails with RegistrationError listing every failing diagnostic |
hinoki check |
both phases (or --phase) |
the waiver file, or --waivers |
exit code 1 |
hinoki mcp |
both phases | the waiver file, or --waivers |
reported to the agent |
Startup enforcement means a broken promise never serves traffic. During a
migration you can pass enforce_rules=False to Hinoki(...): violations are
then logged as a warning instead.
Read the results¶
hinoki check prints one line per finding, with its location and a fix: hint.
This output comes from a deliberately broken project in Hinoki's own tests,
checked from a clone of the repository:
hinoki check tests.projects.rulesapp:create_app --rules tests.projects.rulesapp:rules
tests/projects/rulesapp.py:7: HNK-ACC-001 [violated] GET /health (health) declares no access policy
fix: add access=<policy> to the action (or list it in except_ when it is public on purpose)
tests/projects/rulesapp.py:12: HNK-ACC-001 [violated] POST /items (create) declares no access policy
fix: add access=<policy> to the action (or list it in except_ when it is public on purpose)
tests/projects/rulesapp.py:12: HNK-TXN-001 [violated] POST /items (create) does not declare atomic=True
fix: add atomic=True to the action (or declare it on a RouteGroup(..., atomic=True) group)
2 rule(s): 3 violated, 0 unverifiable, 0 waived
Each status means one thing: violated (demonstrated), unverifiable (the check could not decide: a dynamic import, a pattern that matched nothing, a return type that does not name its schema, or a rule that crashed), waived and warning (a notice about the waiver file itself). Unverifiable fails like a violation; it is never a pass. A warning never fails.
The fix line each rule prints:
| ID | fix: |
|---|---|
HNK-ACC-002 |
name at least one permission in the Access policy of the action |
HNK-API-001 |
return a Schema (for example PostOut.from_model(row)) instead of the Model |
HNK-API-002 |
annotate the action's return type (a Schema, or None for status 204) |
HNK-API-003 |
return Page[Item] and paginate the action instead of returning a list |
HNK-SCH-001 |
remove the field from the response Schema, or return a Schema that does not carry it |
HNK-SCH-002 |
bound the field: Annotated[str, Field(max_length=...)] or one_of=... |
HNK-DB-001 |
name the table with @db.table(...) or table=... on the model |
HNK-DB-002 |
index the column: @db.indexed(" |
HNK-IMP-001 |
move the code to an allowed layer, or depend on it through the layer in between |
hinoki check --format json prints the same diagnostics as versioned data
(schema_version, rules, summary, and per diagnostic rule, severity,
phase, status, message, location, explanation, subject, waiver,
fix) for CI, editors and agents. summary counts each status (violated,
unverifiable, waived, warning) and adds failing, the number that sets
the exit code. schema_version is 2: version 1 reported waiver notices as
violated and had no warning count. Exit codes: 0 clean, 1 failing, 2
the check could not run. The other options are on
Inspect an application.
Accept an exception with a waiver¶
Prefer except_ for things that are public or special by design. A waiver is
for a known violation the owner accepts for a while. It lives in
hinoki-rules.toml at the project root, which hinoki new creates:
# hinoki-rules.toml
[[waiver]]
rule = "HNK-ACC-001"
target = "tests.projects.rulesapp.health"
reason = "liveness probe is public by design"
owner = "platform-team"
expires = 2027-01-31
rule, target, reason and owner are required. target is an fnmatch
pattern on the diagnostic's subject and must be bounded: a literal prefix of at
least five characters containing a dot (shop.api.*, never *). expires is
optional and must be a TOML date, written without quotes; the waiver applies
through that day and expires once the current UTC date is later. The waived diagnostic
keeps its line and gains the decision:
tests/projects/rulesapp.py:7: HNK-ACC-001 [waived] GET /health (health) declares no access policy
fix: add access=<policy> to the action (or list it in except_ when it is public on purpose)
waived: liveness probe is public by design (platform-team, until 2027-01-31)
An expired waiver stops applying and reports HNK-WVR-002; one that matches
nothing reports HNK-WVR-001. Both have status warning: they print as
[warning], count under warning(s) in the summary (summary.warning in JSON)
and never change the exit code. A diagnostic that means "the rule
could not do its job" cannot be waived. An invalid or unreadable file makes
hinoki check exit with 2.
Which waiver file¶
hinoki check, hinoki mcp and application startup read the same file:
- The file named by
Hinoki(waivers=...), or by--waiversoncheckandmcp. A named file must exist. - Otherwise
hinoki-rules.tomlat the project root: the directory of the nearesthinoki.toml, searched from the working directory upwards. Running from a subdirectory of the project finds the same file. - Without a
hinoki.toml,hinoki-rules.tomlin the working directory.
app = Hinoki(rules=rules, waivers="config/hinoki-rules.toml")
A missing default file means no waivers. A directory or a broken symbolic link
with that name is an error, not an absent file. hinoki mcp --waivers PATH also
applies PATH to the app that run_scenario starts.
Waivers at startup¶
Application startup applies the waiver file the same way as hinoki check.
This app requires access on every
action, yet it starts and serves /health because the owner waived it:
# shop/main.py
from hinoki import Actions, Hinoki, Request, http
from hinoki.rules import RuleSet
@http.get("/health")
def health(request: Request) -> dict[str, str]:
return {"status": "ok"}
app = Hinoki(rules=RuleSet(Actions.require_access()), include=[health])
# hinoki-rules.toml
[[waiver]]
rule = "HNK-ACC-001"
target = "shop.main.health"
reason = "liveness probe is public by design"
owner = "platform-team"
Without the waiver, hinoki serve fails at startup with
RegistrationError: 1 rule violation(s).
At startup:
- An absent default file means no waivers.
- An invalid or unreadable file, or a missing file named with
waivers=, fails startup withRegistrationError("invalid waivers: .../hinoki-rules.toml: waiver #1: missing target"), even withenforce_rules=False. - An expired waiver does not apply: the violation fails startup and the
RegistrationErroralso lists theHNK-WVR-002notice. Without a remaining violation the notice is logged as a warning. HNK-WVR-001(unused waiver) is reported only byhinoki checkandhinoki mcp: startup runs only the startup rules, so a waiver for a static rule such asHNK-IMP-001is expected to match nothing there.
Waivers are the owner's decision: tools read the file and never write it. Put it
under CODEOWNERS; the generated AGENTS.md tells agents the same.
Your own rules¶
Subclass hinoki.rules.Rule with a stable id, an explanation, an optional
fix and a check that yields diagnostics. phase defaults to
Phase.STARTUP and severity to Severity.ERROR.
# notes/rules.py
from collections.abc import Iterator
from hinoki.rules import Diagnostic, Project, Rule, qualified, where
class NoDelete(Rule):
id = "NOTES-API-001"
explanation = "This project archives rows instead of deleting them."
fix = "use PATCH to set archived=true"
def check(self, project: Project) -> Iterator[Diagnostic]:
for route in project.app.routes:
if route.method == "DELETE":
yield self.diagnostic(
f"DELETE {route.path} removes a row",
where(route.handler),
subject=qualified(route),
)
Add NoDelete() to the RuleSet. where(obj) gives a file:line location;
qualified(route) gives the subject that waivers match (without a subject the
location is used; an empty subject cannot be waived). A rule that needs side
effects (running code, files, network, a database) lists them in effects and
only runs under hinoki check --allow-effects; at startup it is refused and
reported as unverifiable. RuleSet raises ValueError for an empty ID or the
same ID twice.
Errors and edge cases¶
- A rule that raises is reported as
unverifiablewith "the rule failed to run", never skipped. HNK-IMP-001runs only inhinoki checkandhinoki mcp; it needs the source files of the checked packages (--package, default: the target's top-level package).- The model rules in a project without models are unverifiable, which is why the scaffold keeps them commented out.
See also¶
- Inspect an application: every
hinoki checkoption. - Authentication and access: what
HNK-ACC-001/002ask for. - Build with a coding agent: the same diagnostics for agents through
hinoki mcp.