3 Commits

Author SHA1 Message Date
bcb3da0f18 new task brief 2026-11-10 19:58:06 -05:00
1f7126dca5 abandon auditor 2026-11-10 19:44:13 -05:00
f5e0470cd5 added 1 line to task brief 2026-11-10 19:13:31 -05:00
5 changed files with 508 additions and 204 deletions

View File

@@ -0,0 +1,366 @@
<title>NearBeach Backend Shape</title>
<meta name="claude:viewport-fit-sides" content="cover">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Instrument+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap">
<style>
/* Layout: single reading column (~72ch) with wide breakouts for diagrams and tables; section labels in the margin on desktop. */
:root {
--bg: #f6f7f5;
--surface: #ffffff;
--fg: #17201c;
--muted: #56635d;
--line: #d9dfdb;
--accent: #1f6b52;
--accent-soft: #e2efe9;
--good: #2c7a3f;
--bad: #a8402b;
--warn: #946200;
--code-bg: #eef1ef;
--font-display: "Instrument Sans", "Segoe UI", system-ui, sans-serif;
--font-body: "Instrument Sans", "Segoe UI", system-ui, sans-serif;
--font-mono: "JetBrains Mono", ui-monospace, "SFMono-Regular", Menlo, monospace;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #111613; --surface: #18201c; --fg: #e4ebe7; --muted: #9aa8a1; --line: #2c3832;
--accent: #6cc6a2; --accent-soft: #1d3329; --good: #7ccf8e; --bad: #ef8f78; --warn: #e2b54f; --code-bg: #1e2823;
color-scheme: dark;
}
}
:root[data-theme="dark"] {
--bg: #111613; --surface: #18201c; --fg: #e4ebe7; --muted: #9aa8a1; --line: #2c3832;
--accent: #6cc6a2; --accent-soft: #1d3329; --good: #7ccf8e; --bad: #ef8f78; --warn: #e2b54f; --code-bg: #1e2823;
color-scheme: dark;
}
* { box-sizing: border-box; }
body {
background: var(--bg); color: var(--fg);
font-family: var(--font-body); font-size: 1rem; line-height: 1.6;
padding-left: max(16px, env(safe-area-inset-left, 0px));
padding-right: max(16px, env(safe-area-inset-right, 0px));
padding-block: 3rem 5rem;
}
.wrap { max-width: 60rem; margin: 0 auto; display: grid; gap: 3.5rem; }
header { display: grid; gap: .9rem; max-width: 46rem; }
.eyebrow { font-family: var(--font-mono); font-size: .75rem; letter-spacing: .08em; text-transform: uppercase; color: var(--accent); }
h1 { font-family: var(--font-display); font-size: clamp(2rem, 5vw, 2.9rem); line-height: 1.1; margin: 0; font-weight: 700; letter-spacing: -.02em; text-wrap: balance; }
h2 { font-family: var(--font-display); font-size: 1.55rem; line-height: 1.2; margin: 0; font-weight: 650; letter-spacing: -.01em; text-wrap: balance; }
h3 { font-size: 1.05rem; margin: 0; font-weight: 650; }
p { margin: 0; max-width: 68ch; }
.lede { font-size: 1.15rem; color: var(--muted); }
section { display: grid; gap: 1.2rem; }
.sec-head { display: grid; gap: .4rem; border-top: 1px solid var(--line); padding-top: 1.4rem; }
code, .mono { font-family: var(--font-mono); font-size: .86em; }
code { background: var(--code-bg); padding: .08em .35em; border-radius: 4px; overflow-wrap: anywhere; }
ul { margin: 0; padding-left: 1.2rem; display: grid; gap: .45rem; max-width: 70ch; }
a { color: var(--accent); }
.facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(10.5rem, 1fr)); gap: 0; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); overflow: hidden; }
.fact { padding: .9rem 1rem; border-right: 1px solid var(--line); border-bottom: 1px solid var(--line); display: grid; gap: .15rem; margin: 0 -1px -1px 0; }
.fact b { font-family: var(--font-mono); font-size: 1.35rem; font-weight: 500; font-variant-numeric: tabular-nums; }
.fact span { font-size: .84rem; color: var(--muted); line-height: 1.35; }
.fact.alert b { color: var(--bad); }
.diagram { background: var(--surface); border: 1px solid var(--line); border-radius: 8px; padding: 1.2rem; overflow-x: auto; }
.diagram svg { display: block; min-width: 760px; width: 100%; height: auto; }
.diagram svg text { font-family: var(--font-body); fill: var(--fg); }
.diagram svg .small { font-size: 11px; fill: var(--muted); font-family: var(--font-mono); }
.diagram svg .lbl { font-size: 13px; font-weight: 600; }
.diagram svg .box { fill: var(--surface); stroke: var(--line); stroke-width: 1.5; }
.diagram svg .box.hl { fill: var(--accent-soft); stroke: var(--accent); }
.diagram svg .lane { fill: var(--code-bg); stroke: none; }
.diagram svg .arrow { stroke: var(--muted); stroke-width: 1.5; fill: none; }
.diagram svg .arrow.hl { stroke: var(--accent); }
.diagram svg .ah { fill: var(--muted); }
.diagram svg .ah.hl { fill: var(--accent); }
.caption { font-size: .85rem; color: var(--muted); }
.surfaces { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: 1rem; }
.surface { background: var(--surface); border: 1px solid var(--line); border-radius: 8px; padding: 1.1rem; display: grid; gap: .55rem; align-content: start; min-width: 0; }
.surface .path { font-family: var(--font-mono); font-size: .8rem; color: var(--accent); }
.surface p { font-size: .93rem; }
.surface dl { display: grid; grid-template-columns: auto 1fr; gap: .25rem .8rem; margin: .3rem 0 0; font-size: .85rem; }
.surface dt { color: var(--muted); }
.surface dd { margin: 0; min-width: 0; }
.flow { display: grid; gap: .8rem; }
.flow-steps { list-style: none; padding: 0; margin: 0; display: grid; gap: 0; counter-reset: s; border-left: 2px solid var(--line); max-width: none; }
.flow-steps li { counter-increment: s; position: relative; padding: .55rem 0 .55rem 1.6rem; display: grid; grid-template-columns: minmax(0, 15rem) minmax(0, 1fr); gap: 1rem; }
.flow-steps li::before { content: counter(s); position: absolute; left: -.72rem; top: .6rem; width: 1.3rem; height: 1.3rem; border-radius: 50%; background: var(--bg); border: 2px solid var(--accent); color: var(--accent); font: 600 .7rem/1.05rem var(--font-mono); text-align: center; }
.flow-steps .where { font-family: var(--font-mono); font-size: .8rem; color: var(--muted); overflow-wrap: anywhere; }
.flow-steps .what { font-size: .93rem; }
@media (max-width: 640px) { .flow-steps li { grid-template-columns: minmax(0, 1fr); gap: .2rem; } }
pre.snip { background: var(--code-bg); border-radius: 6px; padding: .9rem 1rem; margin: 0; overflow-x: auto; font-family: var(--font-mono); font-size: .8rem; line-height: 1.55; }
pre.snip .c { color: var(--muted); }
.tbl { overflow-x: auto; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); }
table { width: 100%; border-collapse: collapse; font-size: .92rem; min-width: 640px; }
th, td { text-align: left; vertical-align: top; padding: .7rem .9rem; border-bottom: 1px solid var(--line); }
th { font-size: .74rem; text-transform: uppercase; letter-spacing: .07em; color: var(--muted); font-weight: 600; background: var(--code-bg); }
tr:last-child td { border-bottom: 0; }
td:first-child { font-weight: 600; width: 22%; }
.pro { color: var(--good); }
.con { color: var(--bad); }
.risks { display: grid; gap: .7rem; }
.risk { display: grid; grid-template-columns: 6.5rem minmax(0, 1fr); gap: 1rem; padding: .9rem 1rem; background: var(--surface); border: 1px solid var(--line); border-radius: 8px; }
.risk p { font-size: .93rem; }
.sev { font-family: var(--font-mono); font-size: .7rem; text-transform: uppercase; letter-spacing: .07em; padding: .2rem .5rem; border-radius: 99px; height: fit-content; text-align: center; border: 1px solid currentColor; }
.sev.high { color: var(--bad); }
.sev.med { color: var(--warn); }
.sev.low { color: var(--muted); }
@media (max-width: 560px) { .risk { grid-template-columns: minmax(0, 1fr); gap: .4rem; } .sev { width: fit-content; } }
.note { border-left: 3px solid var(--accent); background: var(--accent-soft); padding: .8rem 1rem; border-radius: 0 6px 6px 0; font-size: .93rem; max-width: 72ch; }
footer { font-size: .82rem; color: var(--muted); border-top: 1px solid var(--line); padding-top: 1rem; }
</style>
<div class="wrap">
<header>
<div class="eyebrow">Architecture briefing · NearBeach codebase</div>
<h1>A Django monolith that renders a shell and hands everything to Vue</h1>
<p class="lede">NearBeach is one Django app with three HTTP surfaces on top of a shared ORM. Django owns routing, auth, permissions and persistence. The UI is a set of Vue components mounted inside Django templates, and they talk mainly to undocumented internal JSON endpoints, not to the public REST API.</p>
</header>
<section>
<div class="facts">
<div class="fact"><b>1</b><span>Django app, packaged as an installable library</span></div>
<div class="fact"><b>246</b><span><code>path()</code> routes in <code>NearBeach/urls.py</code> (pages + AJAX)</span></div>
<div class="fact"><b>24</b><span>DRF viewsets under <code>/api/v0/</code></span></div>
<div class="fact"><b>~50</b><span>models in a single 2,000-line <code>models.py</code></span></div>
<div class="fact"><b>440</b><span><code>is_deleted=False</code> filters written by hand</span></div>
<div class="fact alert"><b>0</b><span><code>transaction.atomic</code> or <code>select_related</code> calls</span></div>
</div>
<p class="caption">Counts come from grep over <code>NearBeach/</code>, excluding migrations, tests and vendored static files.</p>
</section>
<section>
<div class="sec-head">
<div class="eyebrow">Structure</div>
<h2>The layer map</h2>
</div>
<p>Every request, whatever its surface, goes through the same stack: route, auth decorator, NearBeach's own permission decorator, a view function, then the ORM. The interesting part is that the two API-style surfaces duplicate the same business logic.</p>
<div class="diagram">
<svg viewBox="0 0 900 520" role="img" aria-label="Layer diagram of NearBeach request handling">
<defs>
<marker id="a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah" d="M0,0 L10,5 L0,10 z"/></marker>
<marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah hl" d="M0,0 L10,5 L0,10 z"/></marker>
</defs>
<!-- clients -->
<rect class="lane" x="10" y="10" width="880" height="80" rx="6"/>
<text class="small" x="22" y="28">CLIENTS</text>
<rect class="box hl" x="40" y="36" width="360" height="44" rx="5"/>
<text class="lbl" x="56" y="57">Browser: Django HTML + Vue 3 components</text>
<text class="small" x="56" y="72">webpack → NearBeach/static/NearBeach · Vuex · axios</text>
<rect class="box" x="560" y="36" width="300" height="44" rx="5"/>
<text class="lbl" x="576" y="57">External integrations</text>
<text class="small" x="576" y="72">knox token · Basic · session</text>
<!-- surfaces -->
<rect class="lane" x="10" y="110" width="880" height="96" rx="6"/>
<text class="small" x="22" y="128">URL SURFACES</text>
<rect class="box" x="40" y="138" width="230" height="58" rx="5"/>
<text class="lbl" x="54" y="160">Page routes</text>
<text class="small" x="54" y="178">NearBeach/urls.py → HTML</text>
<rect class="box hl" x="300" y="138" width="230" height="58" rx="5"/>
<text class="lbl" x="314" y="160">Internal AJAX routes</text>
<text class="small" x="314" y="178">same urls.py → JSON / text</text>
<rect class="box" x="560" y="138" width="300" height="58" rx="5"/>
<text class="lbl" x="574" y="160">Public REST API</text>
<text class="small" x="574" y="178">urls_api_v0.py · SimpleRouter</text>
<!-- cross-cutting -->
<rect class="lane" x="10" y="226" width="880" height="70" rx="6"/>
<text class="small" x="22" y="244">CROSS-CUTTING</text>
<rect class="box" x="40" y="252" width="490" height="34" rx="5"/>
<text class="small" x="54" y="273">@login_required · @require_http_methods · @check_*_permissions → injects user_level</text>
<rect class="box" x="560" y="252" width="300" height="34" rx="5"/>
<text class="small" x="574" y="273">@check_user_api_permissions (v0)</text>
<!-- handlers -->
<rect class="lane" x="10" y="316" width="880" height="80" rx="6"/>
<text class="small" x="22" y="334">HANDLERS</text>
<rect class="box" x="40" y="342" width="490" height="44" rx="5"/>
<text class="lbl" x="54" y="362">Function views (views/*.py)</text>
<text class="small" x="54" y="378">Django Form validates → model built by hand → serializers.serialize</text>
<rect class="box" x="560" y="342" width="300" height="44" rx="5"/>
<text class="lbl" x="574" y="362">DRF ModelViewSets</text>
<text class="small" x="574" y="378">ModelSerializer (serializers/)</text>
<!-- data -->
<rect class="lane" x="10" y="416" width="880" height="94" rx="6"/>
<text class="small" x="22" y="434">DATA</text>
<rect class="box hl" x="40" y="442" width="300" height="56" rx="5"/>
<text class="lbl" x="54" y="464">Django ORM · models.py</text>
<text class="small" x="54" y="482">soft delete · ObjectAssignment ACL</text>
<rect class="box" x="370" y="442" width="200" height="56" rx="5"/>
<text class="lbl" x="384" y="464">SQL database</text>
<text class="small" x="384" y="482">SQLite in dev</text>
<rect class="box" x="600" y="442" width="260" height="56" rx="5"/>
<text class="lbl" x="614" y="464">File storage</text>
<text class="small" x="614" y="482">private FS · S3/R2 · Azure</text>
<!-- arrows -->
<path class="arrow" d="M150 80 V138" marker-end="url(#a)"/>
<path class="arrow hl" d="M300 80 L400 138" marker-end="url(#ah)"/>
<path class="arrow" d="M370 80 L640 138" marker-end="url(#a)" stroke-dasharray="4 4"/>
<text class="small" x="478" y="104">5 Vue files</text>
<path class="arrow" d="M710 80 V138" marker-end="url(#a)"/>
<path class="arrow" d="M285 196 V252" marker-end="url(#a)"/>
<path class="arrow" d="M710 196 V252" marker-end="url(#a)"/>
<path class="arrow" d="M285 286 V342" marker-end="url(#a)"/>
<path class="arrow" d="M710 286 V342" marker-end="url(#a)"/>
<path class="arrow hl" d="M285 386 L200 442" marker-end="url(#ah)"/>
<path class="arrow hl" d="M710 386 L300 442" marker-end="url(#ah)"/>
<path class="arrow" d="M340 470 H370" marker-end="url(#a)"/>
<path class="arrow" d="M570 470 H600" marker-end="url(#a)"/>
</svg>
</div>
<p class="caption">The dashed arrow is the thin path: only 5 frontend files call <code>/api/v0/</code>. The rest of the roughly 140 axios-using files call internal routes such as <code>project_information/&lt;id&gt;/save/</code>.</p>
</section>
<section>
<div class="sec-head">
<div class="eyebrow">Surfaces</div>
<h2>Three ways in, two codebases of business logic</h2>
</div>
<div class="surfaces">
<div class="surface">
<h3>Page routes</h3>
<div class="path">GET /project_information/&lt;id&gt;/</div>
<p>The function view computes context, encodes it as JSON strings and renders a template. The template does little more than mount Vue.</p>
<dl><dt>Auth</dt><dd>Session + optional 2FA</dd><dt>Output</dt><dd>HTML with JSON in props</dd><dt>Contract</dt><dd>Template ↔ component props</dd></dl>
</div>
<div class="surface">
<h3>Internal AJAX</h3>
<div class="path">POST /project_information/&lt;id&gt;/save/</div>
<p>This is the real application API. Vue sends <code>FormData</code>, a Django <code>Form</code> validates it, and the view writes to models and returns serialized JSON or a URL string.</p>
<dl><dt>Auth</dt><dd>Session + CSRF header</dd><dt>Output</dt><dd>Ad hoc JSON / text</dd><dt>Contract</dt><dd>Undocumented, unversioned</dd></dl>
</div>
<div class="surface">
<h3>REST API v0</h3>
<div class="path">POST /api/v0/project/</div>
<p>DRF viewsets with drf-spectacular docs. This re-implements creates and updates for the same objects, including side effects such as <code>transfer_new_object_uploads</code>.</p>
<dl><dt>Auth</dt><dd>knox token, Basic, session</dd><dt>Output</dt><dd>ModelSerializer JSON</dd><dt>Contract</dt><dd>OpenAPI schema</dd></dl>
</div>
</div>
<p class="note">This means a rule change, such as "a project needs at least one group", has to be made in two places: <code>views/project_views.py</code> with <code>forms.py</code>, and <code>views/api/project_api_view.py</code> with <code>serializers/project_serializer.py</code>. Nothing keeps them in sync except tests.</p>
</section>
<section>
<div class="sec-head">
<div class="eyebrow">Data flow</div>
<h2>Following a project through the system</h2>
</div>
<div class="flow">
<h3>Read path: opening a project page</h3>
<ol class="flow-steps">
<li><span class="where">urls.py</span><span class="what">The <code>project_information/&lt;int:project_id&gt;/</code> route resolves to a plain function view.</span></li>
<li><span class="where">@login_required</span><span class="what">Redirects to the two_factor login if there's no session.</span></li>
<li><span class="where">check_specific_object_permissions</span><span class="what">Looks up <code>project_permissions</code> in <code>FUNCTION_DICT</code>. It intersects the user's <code>UserGroup</code> rows with the project's <code>ObjectAssignment</code> groups, then takes <code>Max("permission_set__project")</code>. The result (0–4) is passed into the view as <code>kwargs["user_level"]</code>. Superusers skip all of this and get 4.</span></li>
<li><span class="where">views/project_views.py</span><span class="what">Runs several <code>.values()</code> / <code>serializers.serialize()</code> queries and turns each result into a JSON string.</span></li>
<li><span class="where">templates/…/project_information.html</span><span class="what">Writes the JSON into attributes such as <code>v-bind:project-results="{{project_results}}"</code>. Django HTML-escapes it, the browser unescapes it, and Vue evaluates it as a JS expression.</span></li>
<li><span class="where">src/js/app.js</span><span class="what">One Vue app mounts on <code>#app</code> and registers every component globally. Each component then fetches its sub-modules (notes, documents, links) over internal AJAX.</span></li>
</ol>
</div>
<div class="flow">
<h3>Write path: saving from the UI</h3>
<pre class="snip"><span class="c">// Vue component (ProjectInformation.vue)</span>
const data_to_send = new FormData();
data_to_send.set("project_name", this.projectNameModel);
this.axios.post(`${this.rootUrl}project_information/${id}/save/`, data_to_send) <span class="c">// X-CSRFTOKEN from cookie</span>
<span class="c"># Django view</span>
form = ProjectForm(request.POST) <span class="c"># validation only, never rendered</span>
if not form.is_valid(): return HttpResponseBadRequest(form.errors)
project.project_name = form.cleaned_data["project_name"]; project.save()
<span class="c"># ...then ObjectAssignment rows, upload transfers, kanban card sync: separate saves, no transaction</span></pre>
</div>
<div class="flow">
<h3>Generic "object data" path</h3>
<p>Notes, tags, links, groups, users, documents and sprints attach to any object type through string-dispatched routes such as <code>object_data/&lt;destination&gt;/&lt;location_id&gt;/add_link/</code> and <code>documentation/&lt;destination&gt;/&lt;location_id&gt;/…</code>. The <code>destination</code> segment selects a model from one of several <code>OBJECT_DICT</code> tables. It's also used directly as an ORM keyword, as in <code>ObjectAssignment.objects.filter(**{destination: location_id})</code>. That's how one view serves ten object types.</p>
</div>
<div class="flow">
<h3>Background path</h3>
<ol class="flow-steps">
<li><span class="where">updatecrontab</span><span class="what">A management command writes cron entries. There's no Celery and no task queue.</span></li>
<li><span class="where">runscheduler</span><span class="what">Reads <code>ScheduledObject</code> and <code>ObjectTemplate</code>, then creates Tasks, Projects or Kanban cards from templates.</span></li>
<li><span class="where">event_hooks.emit()</span><span class="what">A home-made, type-checked event registry used instead of Django signals. Hooks run synchronously in the same process.</span></li>
</ol>
</div>
</section>
<section>
<div class="sec-head">
<div class="eyebrow">The data model</div>
<h2>Permissions live in data, not in Django's auth tables</h2>
</div>
<ul>
<li><strong>Access and capability are separate.</strong> <code>ObjectAssignment</code> answers "can this group see this object". It's one table with about ten nullable foreign keys (project, task, requirement, kanban board…) instead of a <code>GenericForeignKey</code>. <code>PermissionSet</code> answers "what can members of this group do", with a 0–4 level per object type.</li>
<li><strong>The custom <code>Group</code> / <code>UserGroup</code> models replace <code>django.contrib.auth</code> groups and permissions.</strong> <code>has_perm</code> isn't used anywhere. Child objects (change task, kanban card, requirement item) inherit permission from their parent through <code>_fetch_parent_details</code>.</li>
<li><strong>Soft delete is done by hand.</strong> Every model has <code>is_deleted</code>, and there's no custom manager. Each query has to remember the filter, which is why there are 440 of them.</li>
<li><strong>Audit columns are repeated on every model.</strong> <code>date_created</code>, <code>date_modified</code>, <code>change_user</code> and <code>creation_user</code> are copied into each one with no abstract base.</li>
<li><strong>The user model is swappable.</strong> <code>OVERRIDE_AUTH_USER_MODEL</code> sets <code>AUTH_USER_MODEL</code>. Models resolve it through <code>getattr(settings, "AUTH_USER_MODEL", User)</code>.</li>
</ul>
</section>
<section>
<div class="sec-head">
<div class="eyebrow">Trade-offs</div>
<h2>What the structure buys and what it costs</h2>
</div>
<div class="tbl">
<table>
<thead><tr><th>Decision</th><th>Pros</th><th>Cons</th></tr></thead>
<tbody>
<tr><td>Single installable Django app</td><td class="pro">Easy to self-host or pip-install, with one migration history and one deploy unit.</td><td class="con">No internal module boundaries. <code>models.py</code>, <code>forms.py</code> and <code>urls.py</code> are each over 1,000 lines, and every view can import every model.</td></tr>
<tr><td>Django templates mounting Vue</td><td class="pro">Server-side auth and routing come for free. There's no SPA router, and each page ships its data with it, so first paint needs no extra request.</td><td class="con">The data contract is a template string. Props are JS expressions built from escaped JSON. One global bundle registers every component on every page.</td></tr>
<tr><td>Internal AJAX alongside the REST API</td><td class="pro">The UI can change endpoints freely without versioning.</td><td class="con">Business rules are duplicated between Form-based views and DRF serializers, and the UI's real API is undocumented.</td></tr>
<tr><td>Function views + decorators</td><td class="pro">Very explicit and easy to grep. The permission check is visible on every handler.</td><td class="con">Boilerplate is repeated, and decorator order matters. Injecting <code>user_level</code> through kwargs couples every view signature to the decorator.</td></tr>
<tr><td>Custom group/permission-set model</td><td class="pro">Matches the product's domain (teams and object-level access) and can be managed in the UI.</td><td class="con">Bypasses Django's auth tooling. Every check is several queries, computed on every request with no caching.</td></tr>
<tr><td>String-dispatched <code>destination</code> routes</td><td class="pro">One implementation of notes, tags and links serves all object types.</td><td class="con">Stringly-typed polymorphism spread across several <code>OBJECT_DICT</code> copies. URL input reaches ORM keyword names.</td></tr>
<tr><td>Hand-written soft delete and audit fields</td><td class="pro">No hidden manager magic, and recovery is easy.</td><td class="con">One missed filter leaks deleted rows. There are hundreds of chances to miss one.</td></tr>
<tr><td>Cron + management commands</td><td class="pro">No broker or worker infrastructure to run.</td><td class="con">Jobs only run at cron granularity, with no retries or visibility. Event hooks run inline.</td></tr>
</tbody>
</table>
</div>
</section>
<section>
<div class="sec-head">
<div class="eyebrow">For discussion</div>
<h2>Risks a senior reviewer should look at first</h2>
</div>
<div class="risks">
<div class="risk"><span class="sev high">Integrity</span><p><strong>No transactions anywhere.</strong> <code>new_project_save</code> saves the project, then N <code>ObjectAssignment</code> rows, then moves uploads. A failure partway through leaves a project with no groups, which also means nobody but superusers can see it.</p></div>
<div class="risk"><span class="sev high">Security</span><p><strong>URL segments become ORM lookups.</strong> <code>&lt;destination&gt;</code> is an unconstrained <code>str</code> converter, and it reaches <code>filter(**{object_lookup: location_id})</code> in <code>generic_permissions.py</code>. I haven't checked whether a crafted lookup like <code>a__b__startswith</code> can be exploited. Either way, the input should be checked against an allow-list before it reaches the ORM.</p></div>
<div class="risk"><span class="sev med">Performance</span><p><strong>N+1 queries are likely.</strong> There are no <code>select_related</code> or <code>prefetch_related</code> calls. <code>len(queryset)</code> is used where <code>.exists()</code> would do, and permission checks run several queries on every request.</p></div>
<div class="risk"><span class="sev med">Maintainability</span><p><strong>Two write paths per object.</strong> Form views and DRF viewsets drift. Moving the UI onto <code>/api/v0/</code>, or pulling shared logic into a service layer, would remove one of them.</p></div>
<div class="risk"><span class="sev low">Hygiene</span><p><strong>Packaging drift.</strong> <code>pyproject.toml</code> declares <code>Django&gt;=3.1</code> and leaves out DRF, knox and two-factor, while <code>requirements.txt</code> pins 4.2.17+ with them. The <code>local/</code> settings hardcode <code>SECRET_KEY</code> and <code>DEBUG=True</code>, which is acceptable only because it's test-only.</p></div>
</div>
</section>
<section>
<div class="sec-head">
<div class="eyebrow">Orientation</div>
<h2>Where to start reading</h2>
</div>
<ul>
<li><code>local/settings.py</code>: installed apps, middleware order, DRF and knox configuration, storage switches.</li>
<li><code>NearBeach/urls.py</code> and <code>urls_api_v0.py</code>: the full route surface.</li>
<li><code>decorators/check_user_permissions/object_permissions.py</code> and <code>partials/</code>: the permission model in code.</li>
<li><code>models.py</code> around <code>ObjectAssignment</code> (line 989) and <code>PermissionSet</code> (line 1239).</li>
<li><code>views/project_views.py</code> next to <code>views/api/project_api_view.py</code>: the duplication, side by side.</li>
<li><code>views/object_data_views.py</code>: the generic <code>destination</code> pattern, 1,500 lines.</li>
</ul>
</section>
<footer>Based on a read-only static review of the <code>NearBeach/</code> directory on branch <code>project-6</code>. Nothing was executed. Counts come from grep and are approximate.</footer>
</div>

View File

@@ -0,0 +1,63 @@
### 1. Task Description
Build a Django Security Configuration Auditor — a CLI tool that scans Django settings files for production readiness issues. The tool parses Django settings (including `settings.py`, `local_settings.py`, and environment-based configurations) and runs 50+ security checks across categories: DEBUG/SECRET_KEY exposure, security headers (CSP, HSTS, X-Frame-Options), password validators, token/session expiry, CORS, file upload limits, SSL/HTTPS settings, and more. Output formats include human-readable table, JSON, and SARIF for CI/CD integration with exit codes for pipeline gating.
This is a genuine security tool that Django projects need. The NearBeach audit itself revealed exactly the kinds of issues this tool would catch (hardcoded SECRET_KEY, DEBUG=True, missing security headers, non-expiring tokens). Existing tools like `django-check-secrets` or `bandit` don't do Django-specific settings analysis comprehensively.
---
### 2. How to Judge Completion
**Primary check (NearBeach test case):**
1. Mount the NearBeach zip and run the auditor against its `local/settings.py`:
```bash
python -m djangosecauditor /path/to/nearbeach/local/settings.py --format table
```
2. The tool should report **17+ findings** including at minimum:
- CRITICAL: `DEBUG = True`
- CRITICAL: Hardcoded `SECRET_KEY`
- HIGH: Missing `SECURE_SSL_REDIRECT`, `SECURE_HSTS_SECONDS`, `SECURE_CONTENT_TYPE_NOSNIFF`
- HIGH: Missing `X_FRAME_OPTIONS` or set to `SAMEORIGIN` instead of `DENY`
- HIGH: Missing CSP headers (`CONTENT_SECURITY_POLICY`)
- MEDIUM: Weak/absent password validators
- MEDIUM: Missing/short token expiry (`REST_FRAMEWORK` token settings, `SIMPLE_JWT` settings)
- MEDIUM: `ALLOWED_HOSTS` too permissive or `['*']`
- MEDIUM: Missing `SECURE_REFERRER_POLICY`, `SECURE_CROSS_ORIGIN_OPENER_POLICY`
**Hardened settings check:**
3. Create a minimal hardened Django settings file (or fix NearBeach's settings) and run again:
```bash
python -m djangosecauditor /path/to/hardened/settings.py --format json
```
Should report **0 findings** (exit code 0).
**CI/CD integration check:**
4. Run with SARIF output and verify valid SARIF 2.1.0:
```bash
python -m djangosecauditor /path/to/settings.py --format sarif --output results.sarif
```
Validate with `jq` or a SARIF viewer — each finding should have `ruleId`, `level`, `message`, `locations`.
**Test suite:**
5. Run the project's test suite:
```bash
python -m pytest tests/ -v
```
Should pass with 50+ test cases covering rule logic, settings parsing (various formats), output formats, and edge cases.
**Exit codes:**
6. Verify exit codes: `0` = clean, `1` = findings present, `2` = error (invalid settings, parse failure).
---
### 3. Other Notes for Reviewer
This tool automates the manual Django security audit I just performed on NearBeach, which uncovered 17 production-readiness issues. The problem it solves: Django projects ship with insecure defaults, and developers often miss settings that must be explicitly hardened for production. Existing tools (`bandit`, `django-check-secrets`, `safety`) focus on code vulnerabilities or dependency scanning, not Django-specific configuration analysis.
**Why this matters:** A single misconfigured setting (e.g., `DEBUG=True`, weak `SECRET_KEY`, missing HSTS) can lead to full compromise. This tool makes "secure by default" enforceable in CI/CD.
**Architecture:** Pure static analysis — no Django runtime, no database, no network calls. Parses settings as Python AST with env-branch modeling to handle `os.environ.get()`, `django-environ`, `python-decouple`, and conditional blocks (`if "KEY" in os.environ:`) without booting the project. Rule engine is extensible: each check is a class with `check(settings_dict) -> List[Finding]`.
**Scope:** Django settings only. Not scanning `requirements.txt`/`pyproject.toml` for vulnerable dependencies (that's a separate tool's job).
**Safety:** No credentials, no external API calls, no code execution beyond AST parsing. Safe to share and run on any codebase.

View File

@@ -1,64 +0,0 @@
# Selected Task for LiveCompare
## User Selection
- **Chosen**: Task List View with Filtering, Sorting, and Pagination
- **Score**: 25/25
- **Selection Date**: 2025-10-29
- **User Notes**: No modifications - use Task Brief as-is
## Complete Task Brief (Ready for LiveCompare)
### Task Description
NearBeach has task detail views (`task_information`) and task creation (`new_task`), but **no general task list view** for users to see all their tasks across projects. Users must navigate through individual projects or kanban boards to find tasks, which is inefficient for project managers overseeing multiple projects. A dedicated task list with filtering, sorting, and pagination is a standard project management feature that would significantly improve task discoverability and workflow.
### How to Judge Completion
In the repo folder, run the NearBeach start commands:
```bash
cd /workspace/nearbeach
python3 -m pip install --user --break-system-packages -r requirements.txt
python3 manage.py migrate
DJANGO_SUPERUSER_USERNAME=admin DJANGO_SUPERUSER_EMAIL=admin@example.com DJANGO_SUPERUSER_PASSWORD=password python3 manage.py createsuperuser --noinput
python3 manage.py runserver 0.0.0.0:8000
```
Then open `http://localhost:8000` and log in as `admin` / `password`.
**Verification steps:**
1. Navigate to `/tasks/` (new URL) - should display a paginated table of all tasks the user has permission to view
2. Test filtering: select a status from dropdown → table updates to show only tasks with that status
3. Test filtering: select an assignee → shows only tasks assigned to that user
4. Test filtering: select a project → shows only tasks in that project
5. Test filtering: enter date range for start/end dates → shows only tasks in range
6. Test sorting: click column headers (Created, Start Date, End Date, Priority, Status, Project) → toggles asc/desc
7. Test pagination: page size selector (10, 25, 50, 100) and page navigation work
8. Run `python3 manage.py test NearBeach.tests.tests_views.tests_task` - should pass with 10+ new tests covering filtering, sorting, pagination, and permissions
9. Verify permission enforcement: create a second user without access to a project, log in as that user, verify they cannot see tasks from that project
### Other Notes for Reviewer
NearBeach is an open-source Django/Vue project management tool for tracking requirements, projects, tasks, kanban boards, sprints, and RFCs. It's used by small teams to enterprises. The missing task list view is a significant UX gap - users currently have no central place to view all their tasks across projects. This task adds a core feature that project managers would expect, improving daily workflow for anyone managing multiple projects. The implementation touches Django views, templates, URL routing, the existing permission system (group-based via ObjectAssignment), and requires comprehensive tests to ensure permission filtering works correctly.
### Practical Details
- **Setup Commands**:
```bash
cd /workspace/nearbeach
python3 -m pip install --user --break-system-packages -r requirements.txt
python3 manage.py migrate
DJANGO_SUPERUSER_USERNAME=admin DJANGO_SUPERUSER_EMAIL=admin@example.com DJANGO_SUPERUSER_PASSWORD=password python3 manage.py createsuperuser --noinput
python3 manage.py runserver 0.0.0.0:8000
```
- **Key Files Likely Involved**:
- `NearBeach/views/task_views.py` - new `task_list` view function
- `NearBeach/urls.py` - new route for `/tasks/`
- `NearBeach/templates/NearBeach/tasks/task_list.html` - new template with filter sidebar, table, pagination
- `NearBeach/forms.py` - new `TaskFilterForm` for filter validation
- `NearBeach/tests/tests_views/tests_task/` - new test files
- **Potential Challenges**:
- Permission filtering must respect existing `ObjectAssignment` group-based system
- Filter combinations (status + assignee + project + date range) need efficient queryset construction
- Vue frontend may need updates if task list integrates with existing UI patterns
## Next Steps for User
1. Copy the Task Brief above into LiveCompare (Task Description, How to Judge Completion, Other Notes for Reviewer)
2. Download the NearBeach repo zip from the approved repos table in project-rules.md
3. Mount the archive in LiveCompare before your first message
4. Use the File Source URL: `https://github.com/nearbeach/NearBeach`
5. Start the conversation with the model using the Task Description as your first message

View File

@@ -1,170 +1,109 @@
### 1. Task Description
Build a Django Security Configuration Auditor — a CLI tool that scans Django settings files for production readiness issues. The tool parses Django settings (including `settings.py`, `local_settings.py`, and environment-based configurations) and runs 50+ security checks across categories: DEBUG/SECRET_KEY exposure, security headers (CSP, HSTS, X-Frame-Options), password validators, token/session expiry, CORS, file upload limits, SSL/HTTPS settings, and more. Output formats include human-readable table, JSON, and SARIF for CI/CD integration with exit codes for pipeline gating.
Expand NearBeach's search tests from HTTP-status checks into deterministic, data-driven tests that verify actual search results. Candidate 4 identifies explicit TODOs in `NearBeach/tests/tests_views/tests_search/test_search.py` for customer, organisation, and main search; address those gaps and extend coverage across main, customer, organisation, group, user, sprint, tag, notification, and permission-set searches.
This is a genuine security tool that Django projects need. The NearBeach audit itself revealed exactly the kinds of issues this tool would catch (hardcoded SECRET_KEY, DEBUG=True, missing security headers, non-expiring tokens). Existing tools like `django-check-secrets` or `bandit` don't do Django-specific settings analysis comprehensively.
Add at least 20 new test methods covering matching semantics, result counts, pagination, permissions, and closed/include_closed behaviour wherever those features exist in the supplied version. This is a test-engineering task, not a search redesign: preserve existing endpoint contracts and do not implement Candidate 2's unified search or facets.
---
### 2. How to Judge Completion
**Primary check (NearBeach test case):**
1. Mount the NearBeach zip and run the auditor against its `local/settings.py`:
```bash
python -m djangosecauditor /path/to/nearbeach/local/settings.py --format table
```
2. The tool should report **17+ findings** including at minimum:
- CRITICAL: `DEBUG = True`
- CRITICAL: Hardcoded `SECRET_KEY`
- HIGH: Missing `SECURE_SSL_REDIRECT`, `SECURE_HSTS_SECONDS`, `SECURE_CONTENT_TYPE_NOSNIFF`
- HIGH: Missing `X_FRAME_OPTIONS` or set to `SAMEORIGIN` instead of `DENY`
- HIGH: Missing CSP headers (`CONTENT_SECURITY_POLICY`)
- MEDIUM: Weak/absent password validators
- MEDIUM: Missing/short token expiry (`REST_FRAMEWORK` token settings, `SIMPLE_JWT` settings)
- MEDIUM: `ALLOWED_HOSTS` too permissive or `['*']`
- MEDIUM: Missing `SECURE_REFERRER_POLICY`, `SECURE_CROSS_ORIGIN_OPENER_POLICY`
From the NearBeach repository root, create a virtual environment and install the project requirements plus coverage:
**Hardened settings check:**
3. Create a minimal hardened Django settings file (or fix NearBeach's settings) and run again:
```bash
python -m djangosecauditor /path/to/hardened/settings.py --format json
```
Should report **0 findings** (exit code 0).
```bash
python3 -m venv .venv
. .venv/bin/activate
python3 -m pip install -r requirements.txt
python3 -m pip install coverage
```
**CI/CD integration check:**
4. Run with SARIF output and verify valid SARIF 2.1.0:
```bash
python -m djangosecauditor /path/to/settings.py --format sarif --output results.sarif
```
Validate with `jq` or a SARIF viewer — each finding should have `ruleId`, `level`, `message`, `locations`.
Use the supplied repository's documented Django settings and database configuration. Run the existing search suite before making changes and record the baseline; Django's test runner should create and migrate its test database, so a running development server or manually created superuser is not required.
**Test suite:**
5. Run the project's test suite:
```bash
python -m pytest tests/ -v
```
Should pass with 50+ test cases covering rule logic, settings parsing (various formats), output formats, and edge cases.
```bash
python3 manage.py test NearBeach.tests.tests_views.tests_search -v 2
```
**Exit codes:**
6. Verify exit codes: `0` = clean, `1` = findings present, `2` = error (invalid settings, parse failure).
After implementation, rerun that command. All existing search tests and at least 20 additional test methods should pass, with assertions on returned object identities, counts, or pagination metadata rather than only HTTP 200 responses. Inspect the tests to confirm that each of the nine search categories above has meaningful result assertions and that permission cases use ordinary users, not only superusers.
Run the coverage check:
```bash
coverage run --source=NearBeach.views.search_views,NearBeach.views.search \
manage.py test NearBeach.tests.tests_views.tests_search
coverage report -m
```
Both `NearBeach/views/search_views.py` and `NearBeach/views/search/search_objects.py` should individually reach at least 80% statement coverage. Record the actual percentages and uncovered lines; do not omit difficult branches or alter coverage exclusions merely to meet the target.
Finally, run the complete existing suite:
```bash
python3 manage.py test
```
There should be no new failures. If the supplied environment has pre-existing failures or unavailable dependencies, document the exact commands, failures, and comparison with the baseline rather than reporting an unverified pass.
---
### 3. Other Notes for Reviewer
This tool automates the manual Django security audit I just performed on NearBeach, which uncovered 17 production-readiness issues. The problem it solves: Django projects ship with insecure defaults, and developers often miss settings that must be explicitly hardened for production. Existing tools (`bandit`, `django-check-secrets`, `safety`) focus on code vulnerabilities or dependency scanning, not Django-specific configuration analysis.
NearBeach is an open-source Django/Vue project management application used to track projects, tasks, requirements, and related team activity. Search is a navigation mechanism across multiple business objects and administrative records, so a successful HTTP response alone does not show that users can find the right records or that restricted records stay hidden.
**Why this matters:** A single misconfigured setting (e.g., `DEBUG=True`, weak `SECRET_KEY`, missing HSTS) can lead to full compromise. This tool makes "secure by default" enforceable in CI/CD.
The candidate brief reports gaps explicitly documented as TODOs in the existing search tests. Deterministic fixtures and result-level assertions will make filtering and permission regressions visible, providing a safety net for future search maintenance without changing the user interface or adding a new search API. Permission tests are especially important because a search can return plausible results while silently including objects outside a user's authorised groups.
**Architecture:** Pure static analysis — no Django runtime, no database, no network calls. Parses settings as Python AST (handles `from .base import *`, environment variables via `os.environ.get()`, `django-environ`, `python-decouple`). Rule engine is extensible: each check is a class with `check(settings_dict) -> List[Finding]`.
**Scope:** Django settings only. Not scanning `requirements.txt`/`pyproject.toml` for vulnerable dependencies (that's a separate tool's job).
**Safety:** No credentials, no external API calls, no code execution beyond AST parsing. Safe to share and run on any codebase.
Endpoint capabilities and permission rules must be confirmed against the supplied repository before encoding expectations. Not every search type necessarily supports pagination, closed-state filtering, or the same ObjectAssignment-based visibility rules; tests should exercise the actual contract for each type rather than invent uniform behaviour. This document describes planned acceptance criteria, not evidence that the code has already been inspected, changed, or tested.
---
### Implementation Essentials (for Model)
**Project Structure:**
```
djangosecauditor/
├── pyproject.toml # Typer CLI, pytest, rich for table output
├── src/djangosecauditor/
│ ├── __init__.py
│ ├── __main__.py # Entry point: `python -m djangosecauditor`
│ ├── cli.py # Typer app, commands: scan, rules, version
│ ├── parser/
│ │ ├── __init__.py
│ │ ├── settings_parser.py # AST-based parser for settings.py + env
│ │ └── env_resolver.py # Resolves os.environ.get(), django-environ, decouple
│ ├── rules/
│ │ ├── __init__.py
│ │ ├── registry.py # RuleRegistry: discover, load, run rules
│ │ ├── base.py # BaseRule, Finding, Severity(CRITICAL/HIGH/MEDIUM/LOW/INFO)
│ │ ├── debug.py # DEBUG, SECRET_KEY rules
│ │ ├── headers.py # Security headers (HSTS, CSP, X-Frame, etc.)
│ │ ├── auth.py # Password validators, token/session expiry
│ │ ├── cors.py # CORS_ORIGIN_ALLOW_ALL, CORS_ALLOW_CREDENTIALS
│ │ ├── ssl.py # SECURE_SSL_REDIRECT, SESSION_COOKIE_SECURE, CSRF_COOKIE_SECURE
│ │ ├── uploads.py # FILE_UPLOAD_MAX_MEMORY_SIZE, DATA_UPLOAD_MAX_MEMORY_SIZE
│ │ └── misc.py # ALLOWED_HOSTS, CSRF_TRUSTED_ORIGINS, etc.
│ ├── output/
│ │ ├── __init__.py
│ │ ├── formatter.py # BaseFormatter + TableFormatter, JSONFormatter, SARIFFormatter
│ │ └── sarif.py # SARIF 2.1.0 schema builder
│ └── utils/
│ ├── __init__.py
│ └── exit_codes.py # ExitCode enum
├── tests/
│ ├── test_parser.py
│ ├── test_rules_debug.py
│ ├── test_rules_headers.py
│ ├── test_rules_auth.py
│ ├── test_rules_cors.py
│ ├── test_rules_ssl.py
│ ├── test_rules_uploads.py
│ ├── test_rules_misc.py
│ ├── test_output_table.py
│ ├── test_output_json.py
│ ├── test_output_sarif.py
│ ├── test_cli.py
│ └── fixtures/
│ ├── vulnerable_settings.py
│ ├── hardened_settings.py
│ ├── env_based_settings.py
│ └── multi_file_settings/
└── README.md
```
**Scope and Starting Points:**
- Start with `NearBeach/tests/tests_views/tests_search/test_search.py`, its TODOs, and neighbouring search tests.
- Read `NearBeach/views/search_views.py`, `NearBeach/views/search/search_objects.py`, URL routing, and the forms used by the endpoints before designing requests.
- Confirm request methods, parameter names, response shapes, pagination behaviour, and permission requirements from the supplied code.
- Reuse existing test conventions, fixture helpers, and authentication setup where appropriate.
- Keep changes in tests and test data by default. If a test reveals a production defect, explain it and agree on a separate fix rather than silently changing search behaviour or weakening the assertion.
**Core Rules (50+ checks, grouped):**
**Deterministic Test Data:**
- Prefer class-level `setUpTestData()` with Django `TestCase` where compatible with the existing suite; use transactional tests only when required.
- Create small, explicit datasets with known descriptions, names, statuses, dates, users, groups, and object assignments.
- Include matching records, deliberate near-matches, unrelated records, and restricted records so incorrect filtering cannot pass accidentally.
- Use synthetic usernames and addresses, not personal information.
- Create enough records to cross real pagination boundaries without relying on unrelated fixtures.
- Use fixed or controlled timestamps when dates or ordering affect assertions.
- If reusable fixtures are preferable, place them alongside existing fixture conventions and document the records on which assertions depend.
| Category | Rules (examples) |
|----------|------------------|
| **Debug/Secrets** | DEBUG=True, SECRET_KEY hardcoded/weak/short, SECRET_KEY_FALLBACKS |
| **Security Headers** | SECURE_HSTS_SECONDS>=31536000, SECURE_HSTS_INCLUDE_SUBDOMAINS, SECURE_HSTS_PRELOAD, SECURE_CONTENT_TYPE_NOSNIFF, SECURE_REFERRER_POLICY, SECURE_CROSS_ORIGIN_OPENER_POLICY, X_FRAME_OPTIONS=DENY, CONTENT_SECURITY_POLICY present |
| **SSL/HTTPS** | SECURE_SSL_REDIRECT, SESSION_COOKIE_SECURE, CSRF_COOKIE_SECURE, SECURE_PROXY_SSL_HEADER |
| **Auth/Tokens** | AUTH_PASSWORD_VALIDATORS (4+ validators), REST_FRAMEWORK token expiry, SIMPLE_JWT access/refresh lifetime, PASSWORD_RESET_TIMEOUT |
| **CORS** | CORS_ORIGIN_ALLOW_ALL=False, CORS_ALLOW_CREDENTIALS=False, CORS_ALLOWED_ORIGINS explicit |
| **Hosts/Origins** | ALLOWED_HOSTS not ['*'], CSRF_TRUSTED_ORIGINS explicit, CSRF_COOKIE_SAMESITE=Lax/Strict |
| **Uploads** | FILE_UPLOAD_MAX_MEMORY_SIZE reasonable, DATA_UPLOAD_MAX_MEMORY_SIZE reasonable, FILE_UPLOAD_PERMISSIONS |
| **Sessions** | SESSION_COOKIE_AGE, SESSION_COOKIE_HTTPONLY, SESSION_COOKIE_SAMESITE, SESSION_EXPIRE_AT_BROWSER_CLOSE |
| **CSP** | CONTENT_SECURITY_POLICY dict with default-src, script-src, style-src, img-src, connect-src, frame-ancestors |
**Coverage Matrix:**
**CLI Interface:**
```bash
djangosecauditor scan [PATH] --format [table|json|sarif] --output [FILE] --severity [critical|high|medium|low|info] --ignore-rules [RULE_IDS] --config [FILE]
djangosecauditor rules # List all rules with IDs, severity, description
djangosecauditor version
```
| Area | Required assertions |
|------|---------------------|
| Exact and partial matching | Expected IDs are returned; unrelated and near-matching records are excluded according to the endpoint's actual matching rules. |
| Case insensitivity | Case variants return the same matching records where searches use case-insensitive matching. |
| Multi-term queries | Where terms are space-split and ANDed, only records matching every term are returned; records matching just one term are excluded. |
| Empty and no-match queries | Assert the endpoint's defined result shape and counts, including a genuinely empty result set. |
| Pagination | Check first page, second page, final boundary, and beyond-last-page behaviour on endpoints that paginate. Verify no overlap or missing expected records across valid pages. |
| Permissions | Ordinary users see permitted records and cannot see restricted records; include users with no relevant access and overlapping group assignments. |
| Closed/include_closed | Closed records are excluded or included as specified by the actual supported toggle, without changing visibility permissions. |
| Counts | Returned totals or per-type counts agree with the accessible matching records, not the unfiltered dataset. |
| Search categories | Main, customer, organisation, group, user, sprint, tag, notification, and permission-set searches each receive result-level assertions. |
**Settings Parsing Strategy:**
- Parse `settings.py` as AST (don't execute — avoids side effects, import loops, missing deps)
- Handle: `from .base import *`, `from .production import *`, `os.environ.get('KEY', 'default')`, `env('KEY')` (django-environ), `config('KEY')` (python-decouple)
- Recursively resolve imported modules up to 3 levels
- Return merged dict: `{setting_name: value}` with unresolved env vars marked as `EnvVar('KEY', default)`
**Permissions:**
- Build explicit authorised and unauthorised users/groups using the existing permission model.
- Exercise ObjectAssignment-based filtering where it applies; verify administrative and user-specific endpoints against their own rules.
- For notifications, verify recipient isolation if supported by the endpoint contract.
- Include an object assigned through multiple accessible groups to check that joins do not duplicate results or inflate counts.
- Keep superuser behaviour in a separate case so it cannot mask missing permission setup.
**Output Formats:**
- **Table** (default): Rich table with columns: Severity, Rule ID, Setting, Message, File:Line
- **JSON**: Array of findings with `rule_id`, `severity`, `setting`, `message`, `file`, `line`, `value` (redacted for secrets)
- **SARIF**: 2.1.0 schema, each finding = `result` with `ruleId`, `level` (error/warning/note), `message`, `locations` (physicalLocation with uri, region)
**Assertions and Organisation:**
- Use descriptive test names and `subTest()` for closely related input variants, while still adding at least 20 new test methods.
- Compare exact sets of IDs when order is unspecified; assert ordered sequences only when ordering is part of the contract.
- Check both inclusion and exclusion, and validate totals or metadata when exposed.
- Prefer client requests and real database records over mocking the search/filtering logic being tested.
- Replace TODO comments only when their intended result-level coverage is implemented.
- Do not introduce facet tests unless facets already exist in the supplied repository; Candidate 2 is not a prerequisite.
**Testing:**
- Fixture: `vulnerable_settings.py` (NearBeach-like, 17+ issues)
- Fixture: `hardened_settings.py` (0 issues)
- Fixture: `env_based_settings.py` (uses os.environ, django-environ)
- Fixture: `multi_file_settings/` (base.py + production.py + local.py)
- Each rule: unit test with positive/negative cases
- CLI: integration tests for each format, exit codes, filtering
**Config File (optional, stretch):**
- `djangosecauditor.toml` or `pyproject.toml` `[tool.djangosecauditor]`
- `ignore_rules = ["DJANGO-SEC-001"]`
- `severity_threshold = "high"`
- `custom_rules_path = "./my_rules/"`
**Dependencies:**
- `typer` + `rich` (CLI/table)
- `pydantic` (settings models, SARIF)
- `pytest` (testing)
- No Django dependency (pure AST parsing)
**Verification Evidence:**
- Record baseline and final search-suite results, including test counts and failures.
- Record the coverage command and individual coverage percentages for both target modules.
- Summarise the full-suite result and distinguish pre-existing/environment failures from regressions.
- List changed test/fixture files and any endpoint limitations discovered during implementation.