Skip to content

The platform for continuously improving AI agents.

Enforce API key permissions, block bare pushes from main and cap journey workers (#263)

Freyam Mehta2b49781bc8b4
diff --git a/.agents/hooks/bash_guard.py b/.agents/hooks/bash_guard.py
index ea460e5b..c74bbbe0 100755
--- a/.agents/hooks/bash_guard.py
+++ b/.agents/hooks/bash_guard.py
@@ -9,7 +9,9 @@ from guards import check_command
def main():
- verdict = check_command(payload.command(payload.read()))
+ data = payload.read()
+ command = payload.command(data)
+ verdict = check_command(command, payload.branch(data) if "push" in command else None)
if not verdict:
return
decision, reason = verdict
diff --git a/.agents/hooks/guards.py b/.agents/hooks/guards.py
index ea1ec4a5..10174376 100644
--- a/.agents/hooks/guards.py
+++ b/.agents/hooks/guards.py
@@ -2,6 +2,11 @@
import re
+_PUSH_MAIN = "Direct push to main is not allowed. Push to the current feature branch and open a PR."
+_PUSH = re.compile(
+ r"(^|[;&|\n(){}])\s*git(\s+-[Cc]\s+[^\s-]\S*|\s+-(?![Cc]\s)[^\s=]*(=\S*)?)*\s+push\b"
+)
+
_RULES = [
(
# gh pr edit aborts on this repo (Projects-classic GraphQL deprecation)
@@ -21,7 +26,7 @@ _RULES = [
(
r"git push[^;&|]*[\s:/](main|master)(?=$|[\s;&|])",
"deny",
- "Direct push to main is not allowed. Push to the current feature branch and open a PR.",
+ _PUSH_MAIN,
),
(
r"(^|[;&|]\s*)make clean\b|docker compose down[^;&|]*-v\b",
@@ -51,15 +56,18 @@ _RULES = [
_QUOTED = re.compile(r"'[^']*'|\"[^\"]*\"")
-def check_command(command):
+def check_command(command, branch=None):
"""Return (decision, reason) for a shell command, or None to stay out of the way.
Quoted strings are blanked first so a grep for a guarded phrase is not itself denied.
The commit-trailer rule reads the raw command because the trailer lives in the message.
+ ``branch`` is the checked-out branch, so a bare ``git push`` from main is denied too.
"""
if not command:
return None
bare = _QUOTED.sub("''", command)
+ if branch in ("main", "master") and _PUSH.search(bare):
+ return "deny", _PUSH_MAIN
for pattern, decision, reason in _RULES:
haystack = command if "Co-" in pattern else bare
if re.search(pattern, haystack):
diff --git a/.agents/hooks/payload.py b/.agents/hooks/payload.py
index d1f68f8d..a258157c 100644
--- a/.agents/hooks/payload.py
+++ b/.agents/hooks/payload.py
@@ -35,6 +35,20 @@ def edited_paths(payload):
return [os.path.normpath(os.path.join(cwd, p)) for p in paths]
+def branch(payload):
+ try:
+ return subprocess.run(
+ ["git", "rev-parse", "--abbrev-ref", "HEAD"],
+ cwd=payload.get("cwd") or os.getcwd(),
+ capture_output=True,
+ text=True,
+ # Under the 5 s hook timeout, or the runner drops the verdict.
+ timeout=2,
+ ).stdout.strip()
+ except Exception:
+ return ""
+
+
def project_root(payload):
root = os.environ.get("CLAUDE_PROJECT_DIR")
if root:
diff --git a/.agents/skills/backend-architecture/references/auth-and-billing.md b/.agents/skills/backend-architecture/references/auth-and-billing.md
index 9e3d3e58..66187e90 100644
--- a/.agents/skills/backend-architecture/references/auth-and-billing.md
+++ b/.agents/skills/backend-architecture/references/auth-and-billing.md
@@ -11,7 +11,7 @@ Tenancy is project-scoped (`User` ↔ `Project` through `ProjectMembership`), wi
## API keys
-`scope=account` (every project the user belongs to) or `scope=project` (one `resourceIds` entry). REST and MCP `create_api_key` share `APIToken.create_for_user` and the Console dialog's fields: name, description, expiry of 30, 90, 180 or 365 days, or 0 for never. MCP omits `project_id` for an account key. The plaintext is returned once. Over MCP, a project credential cannot mint an account key; guests cannot mint keys. MCP OAuth credentials work only on MCP (mcp skill).
+`scope=account` (every project the user belongs to) or `scope=project` (one `resourceIds` entry). REST and MCP `create_api_key` share `APIToken.create_for_user` and the Console dialog's fields: name, description, expiry of 30, 90, 180 or 365 days, or 0 for never. MCP omits `project_id` for an account key. The plaintext is returned once. A key creates keys only with permissions it holds; a project key only for its own project, an account key for any project its user belongs to (`iam.delegation_denial`, REST and MCP). Guests cannot mint keys. `APITokenBackend.authenticate` refuses REST writes from a key without `write`; MCP resolves keys through `resolve()` and filters tools by permission instead. MCP OAuth credentials work only on MCP (mcp skill).
## Billing
diff --git a/.agents/skills/pr-etiquette/SKILL.md b/.agents/skills/pr-etiquette/SKILL.md
index 6f786742..15ad07b9 100644
--- a/.agents/skills/pr-etiquette/SKILL.md
+++ b/.agents/skills/pr-etiquette/SKILL.md
@@ -117,7 +117,7 @@ Always re-read the PR afterwards (`gh pr view <n>`) to confirm the edit landed.
## Conventions
-- Never push directly to `main`; land work via a PR from a feature branch. A hook blocks a push that names `main` or `master`; a bare `git push` while on `main` is not caught.
+- Never push directly to `main`; land work via a PR from a feature branch. A hook blocks a push that names `main` or `master`, and any `git push` while `main` or `master` is checked out.
- Verify the actual current branch with `git status -sb` before pushing — the session-start banner can be stale.
- Commit messages: short subject + at most one body line. No co-author trailers.
- For fix-sweep PRs, a before/after table in the body is the house style.
diff --git a/.github/workflows/sdk-publish.yml b/.github/workflows/sdk-publish.yml
index f724dca1..deef1584 100644
--- a/.github/workflows/sdk-publish.yml
+++ b/.github/workflows/sdk-publish.yml
@@ -1,7 +1,7 @@
name: SDK Build and Publish
-# Publishes the in-repo SDK. Never runs on ordinary pushes to platform main —
-# only on explicit version tags or published releases.
+# Publishes the in-repo SDK on every push to main that touches overmind/ and on
+# published releases.
on:
push:
branches: [main]
diff --git a/Makefile b/Makefile
index cf0f7e1e..1f89262a 100644
--- a/Makefile
+++ b/Makefile
@@ -68,4 +68,4 @@ test-serial: ## Run all tests serially (for debugging)
test-journeys: ## Run end-to-end journeys on the live stack (needs compose Postgres and Redis)
TEST_REDIS_URL=redis://localhost:6379/15 OVERMIND_JOURNEY_XDIST=1 \
- uv run pytest tests/journeys -n $(WORKERS) --dist loadfile -v -o console_output_style=count --durations=10 $(test_args)
+ uv run pytest tests/journeys -n $(WORKERS) --maxprocesses 6 --dist loadfile -v -o console_output_style=count --durations=10 $(test_args)
diff --git a/overbae/api/auth_keys.py b/overbae/api/auth_keys.py
index dc12bd06..587768f0 100644
--- a/overbae/api/auth_keys.py
+++ b/overbae/api/auth_keys.py
@@ -1,11 +1,17 @@
from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import generics, serializers, status
+from rest_framework.exceptions import PermissionDenied
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from overbae.models import APIToken
-from overbae.models.iam import API_KEY_EXPIRY_DAYS, account_scope, project_scope
+from overbae.models.iam import (
+ API_KEY_EXPIRY_DAYS,
+ account_scope,
+ delegation_denial,
+ project_scope,
+)
class APITokenScopeSerializer(serializers.Serializer):
@@ -123,6 +129,12 @@ class APITokenListCreateView(generics.ListCreateAPIView):
project, scope_doc = _resolve_create_scope(ser.validated_data, request.user)
if isinstance(project, Response):
return project
+ if isinstance(request.auth, APIToken):
+ denial = delegation_denial(
+ request.auth.scope, project.id if project else None, scope_doc["permission"]
+ )
+ if denial:
+ raise PermissionDenied(denial)
raw, instance = APIToken.create_for_user(
request.user,
diff --git a/overbae/api/authentication.py b/overbae/api/authentication.py
index 570f691f..9713f810 100644
--- a/overbae/api/authentication.py
+++ b/overbae/api/authentication.py
@@ -44,10 +44,22 @@ class APITokenBackend(BaseAuthentication):
"""``X-Api-Key: <key>`` or ``Authorization: Bearer <key>``.
Must stay ahead of JWT in the auth class list: an unmatched JWT-shaped value
- returns None so simplejwt gets its turn.
+ returns None so simplejwt gets its turn. A key without ``write`` may only read;
+ the check lives here for the same reason as the guest gate.
"""
def authenticate(self, request):
+ result = self.resolve(request)
+ if (
+ result
+ and request.method not in SAFE_METHODS
+ and "write" not in result[1].scope.get("permission", [])
+ ):
+ raise exceptions.PermissionDenied("This API key is read-only.")
+ return result
+
+ def resolve(self, request):
+ """The key's (user, token) without the method check; MCP filters tools by permission."""
raw = self._extract_key(request)
if raw is None:
return None
diff --git a/overbae/api/otlp.py b/overbae/api/otlp.py
index e0d556eb..e66c8fb1 100644
--- a/overbae/api/otlp.py
+++ b/overbae/api/otlp.py
@@ -774,8 +774,8 @@ def _build_spans_for_resource(
return spans, project
-# Updated when the same ``span_id`` is re-ingested. The experiment FKs
-# (capability / job / iteration) are owned by ``process_span`` and must stay out.
+# Updated when the same ``span_id`` is re-ingested. The linkage FKs
+# (capability / conversation) are owned by ``process_span`` and must stay out.
_SPAN_UPSERT_FIELDS = [
"name",
"kind",
diff --git a/overbae/modal/models.json b/overbae/modal/models.json
index ac051867..70b8ea8b 100644
--- a/overbae/modal/models.json
+++ b/overbae/modal/models.json
@@ -1,5 +1,5 @@
{
- "comment": "Single source of truth for all models supported by the Overmind platform. Each entry carries a 'backend' field (together | baseten). Models available on multiple backends appear as separate entries with their own inference/finetuning sub-configs. inference.gpu_type is the default for base-model inference (BF16 serving, single GPU). inference.lora_supported declares verified shared-base LoRA support for MoE models; dense models support it by default. inference.min_vram_gb is a measured minimum GPU capacity enforced for automatic inference selection, including short contexts. num_attn_layers/num_kv_heads/head_dim are used by gpu_selector.py to derive the optimal GPU + concurrency for a model at its serving max_model_len, including input and reserved output. For hybrid models (Qwen3.5), num_attn_layers counts only full-attention layers. Use model_registry.py helpers to filter by backend. To add/remove models, edit only this file. Baseten models train LoRA or Full on H100s/H200s via our TRL train.py; finetuning.context_length is the model's max trainable context = HF config max_position_embeddings (Qwen2.5 32768, Qwen3 dense 40960, Qwen3.5/3.6/3.8/Coder 262144, Llama 3.x / GPT-OSS / Antares-1B 131072, Antares-350M 32768, LFM2.5-230M/350M/1.2B 32768 per Liquid's documented window, LFM2.5-8B-A1B 128000, LFM2.5-2.6B 131072; train.py applies no RoPE scaling). context_length (top-level) is the published inference window (YaRN-extended where the vendor documents it: Qwen2.5\u22657B and Qwen3 dense \u2192 131072; Qwen2.5-0.5B stays 32768). Baseten itself imposes no per-model training context limit (max_seq_len up to 1048576, docs.baseten.co/engines/engine-builder-llm/engine-builder-config; training is arbitrary code, docs.baseten.co/training/getting-started). The runner snaps the actual training MAX_LENGTH up from dataset stats using finetuning_providers.<backend> policy below. pricing.train_from_usd is a marketing 'from' floor for a typical small LoRA run (Baseten H100 $0.10833/GPU-min = $6.50/h, baseten.co/pricing): \u226414B anchored on Jul 2026 Baseten-invoiced job averages; larger sizes estimated from typical GPU-minutes \u00d7 rate on 1\u00d7H100 (\u226472B). pricing.run_from_usd_per_1m_output is serving per 1M output tokens (Modal L4/L40S self-hosted vLLM floors; MoE uses active-param band). group is the marketing library tab label (Group on /models specs); provider comes from providers.display_names. model.marketing holds buyer-facing copy per model (pitch, description, overview, good_for) for the marketing site detail pages. group is only the library tab/filter label. library_filters defines the marketing /models multi-select filters (use_case, tier, context); each model.use_cases lists which use-case filter ids apply. tier/context filters match model.tier and model.context_length against library_filters entries. The order of the models array is the catalog display order within a tier (newest generation first); recommendation ranking is decided by benchmark grades, not by this order.",
+ "comment": "Single source of truth for all models supported by the Overmind platform. Each entry carries a 'backend' field (baseten | together | decision). Models available on multiple backends appear as separate entries with their own inference/finetuning sub-configs. inference.gpu_type is the default for base-model inference (BF16 serving, single GPU). inference.lora_supported declares verified shared-base LoRA support for MoE models; dense models support it by default. inference.min_vram_gb is a measured minimum GPU capacity enforced for automatic inference selection, including short contexts. num_attn_layers/num_kv_heads/head_dim are used by gpu_selector.py to derive the optimal GPU + concurrency for a model at its serving max_model_len, including input and reserved output. For hybrid models (Qwen3.5), num_attn_layers counts only full-attention layers. Use model_registry.py helpers to filter by backend. To add/remove models, edit only this file. Baseten models train LoRA or Full on H100s/H200s via our TRL train.py; finetuning.context_length is the model's max trainable context = HF config max_position_embeddings (Qwen2.5 32768, Qwen3 dense 40960, Qwen3.5/3.6/3.8/Coder 262144, Llama 3.x / GPT-OSS / Antares-1B 131072, Antares-350M 32768, LFM2.5-230M/350M/1.2B 32768 per Liquid's documented window, LFM2.5-8B-A1B 128000, LFM2.5-2.6B 131072; train.py applies no RoPE scaling). context_length (top-level) is the published inference window (YaRN-extended where the vendor documents it: Qwen2.5\u22657B and Qwen3 dense \u2192 131072; Qwen2.5-0.5B stays 32768). Baseten itself imposes no per-model training context limit (max_seq_len up to 1048576, docs.baseten.co/engines/engine-builder-llm/engine-builder-config; training is arbitrary code, docs.baseten.co/training/getting-started). The runner snaps the actual training MAX_LENGTH up from dataset stats using finetuning_providers.<backend> policy below. pricing.train_from_usd is a marketing 'from' floor for a typical small LoRA run (Baseten H100 $0.10833/GPU-min = $6.50/h, baseten.co/pricing): \u226414B anchored on Jul 2026 Baseten-invoiced job averages; larger sizes estimated from typical GPU-minutes \u00d7 rate on 1\u00d7H100 (\u226472B). pricing.run_from_usd_per_1m_output is serving per 1M output tokens (Modal L4/L40S self-hosted vLLM floors; MoE uses active-param band). group is the marketing library tab label (Group on /models specs); provider comes from providers.display_names. model.marketing holds buyer-facing copy per model (pitch, description, overview, good_for) for the marketing site detail pages. group is only the library tab/filter label. library_filters defines the marketing /models multi-select filters (use_case, tier, context); each model.use_cases lists which use-case filter ids apply. tier/context filters match model.tier and model.context_length against library_filters entries. The order of the models array is the catalog display order within a tier (newest generation first); recommendation ranking is decided by benchmark grades, not by this order.",
"providers": {
"comment": "Friendly display name per model-id prefix (the part before the first '/'), keyed lowercase, under display_names. Used by overbae.services.model_library to label each model's family/provider on the public /library pages. Unknown prefixes fall back to a title-cased version of the raw prefix \u2014 add an entry here instead of hardcoding it in Python.",
"display_names": {
diff --git a/overbae/models/iam.py b/overbae/models/iam.py
index 59484539..075e4c92 100644
--- a/overbae/models/iam.py
+++ b/overbae/models/iam.py
@@ -182,6 +182,17 @@ def project_scope(project_id, *, permission: list[str] | None = None) -> dict:
}
+def delegation_denial(scope: dict, project_id, permission: list[str] | None = None) -> str | None:
+ """Why a key holding ``scope`` cannot create a key for ``project_id`` (None: account)."""
+ if scope.get("scope") != "account" and (
+ project_id is None or str(project_id) not in scope.get("resourceIds", [])
+ ):
+ return "A project API key can only create a key for its own project."
+ if not set(permission or ["read", "write"]) <= set(scope.get("permission", [])):
+ return "An API key can only create a key with permissions it holds."
+ return None
+
+
class APIToken(models.Model):
"""Only the SHA-256 hash is stored; the plaintext key is returned once.
diff --git a/overbae/services/mcp/auth.py b/overbae/services/mcp/auth.py
index b8942bb2..1eedae10 100644
--- a/overbae/services/mcp/auth.py
+++ b/overbae/services/mcp/auth.py
@@ -83,7 +83,7 @@ def _authenticate_sync(scope: Scope) -> MCPContext:
),
)
try:
- result = APITokenBackend().authenticate(request)
+ result = APITokenBackend().resolve(request)
except exceptions.AuthenticationFailed as exc:
raise _auth_error(str(exc.detail)) from None
diff --git a/overbae/services/mcp/resources.py b/overbae/services/mcp/resources.py
index ac9529c6..44dcaf7b 100644
--- a/overbae/services/mcp/resources.py
+++ b/overbae/services/mcp/resources.py
@@ -253,7 +253,7 @@ def _dataset_upload_resource(uri: str) -> dict:
"values": ["decision_train", "decision_eval", "chat_train", "model_eval"],
"scope": "Declare on the final step. Validates the complete output, including nested decision targets, in both preview and publish. Technical compatibility does not establish target meaning.",
},
- "batch_rows": "Optional per-step integer 1–100000. The script runs in separate bounded containers over consecutive row batches; outputs concatenate in source order and all steps publish atomically. Declare only for independent row transformations, never global sorting, grouping, splitting or deduplication. Choose a batch whose expanded JSONL input and output each fit half the declared scratch_mb. Each batch gets the package time limit; progress reports completed batches and rows. Global row checks run after concatenation.",
+ "batch_rows": "Optional per-step integer 1–100000. The script runs as a separate bounded sandbox run for each consecutive row batch; outputs concatenate in source order and all steps publish atomically. Declare only for independent row transformations, never global sorting, grouping, splitting or deduplication. Choose a batch whose expanded JSONL input and output each fit half the declared scratch_mb. Each batch gets the package time limit; progress reports completed batches and rows. Global row checks run after concatenation.",
"corrections": "Edit the same recipe family and run the corrected package from its original source cell. Successful publication replaces the displayed process; no repair-history view or disconnected prepared-v2 sources. Pinned training and evaluation inputs remain reproducible internally. Recipe ownership is project-scoped, not tied to the dataset or capability; reuse only when source and task semantics are compatible.",
"source_boundary": "Upload original source bytes once with pinned upstream revision metadata. Register retained transformation code before full-data processing. Locally prepared derivatives must use lineage-bound external import, never masquerade as an independent source upload.",
"script_arguments": ["input.jsonl", "output.jsonl", "parameters.json"],
diff --git a/overbae/services/mcp/tools_projects.py b/overbae/services/mcp/tools_projects.py
index 275ae8e4..faf20ad2 100644
--- a/overbae/services/mcp/tools_projects.py
+++ b/overbae/services/mcp/tools_projects.py
@@ -5,6 +5,7 @@ from django.conf import settings
from pydantic import BaseModel, ConfigDict, Field
from overbae.models import APIToken
+from overbae.models.iam import delegation_denial
from overbae.services import activity
from overbae.services.mcp.context import accessible_projects
from overbae.services.mcp.contracts.activity import ReportOnboardingInput, ReportOnboardingOutput
@@ -63,19 +64,11 @@ def list_projects(payload, context):
def _key_project(payload: CreateApiKeyInput, context):
scope = context.token.scope if isinstance(context.token.scope, dict) else {}
- account = scope.get("scope") == "account"
+ denial = delegation_denial(scope, payload.project_id)
+ if denial:
+ raise MCPError("permission_denied", denial)
if payload.project_id is None:
- if account:
- return None
- raise MCPError(
- "permission_denied",
- "A project API key can only create a key for its own project.",
- )
- if not account and str(payload.project_id) != str(context.project.id):
- raise MCPError(
- "permission_denied",
- "A project API key can only create a key for its own project.",
- )
+ return None
try:
selected = UUID(str(payload.project_id))
except ValueError:
diff --git a/tests/test_api_tokens.py b/tests/test_api_tokens.py
index 1db4ed3a..71a101b3 100644
--- a/tests/test_api_tokens.py
+++ b/tests/test_api_tokens.py
@@ -93,6 +93,59 @@ def test_account_api_key_can_mint_project_scoped_key():
assert r.data["key"].startswith("ovr_")
+def test_project_api_key_mints_only_for_its_own_project():
+ user, own, sibling = make_user(), make_project(), make_project()
+ ProjectMembership.objects.create(user=user, project=own)
+ ProjectMembership.objects.create(user=user, project=sibling)
+ client, _ = _api_key_client(user, project=own)
+
+ account = {"name": "x", "scope": {"scope": "account", "permission": ["read", "write"]}}
+ pinned = {
+ "name": "x",
+ "scope": {"scope": "project", "resourceIds": [str(sibling.id)], "permission": ["read"]},
+ }
+ for body in (account, {"name": "x", "project": str(sibling.id)}, pinned):
+ r = client.post("/api/auth/api-keys/", body, format="json")
+ assert r.status_code == status.HTTP_403_FORBIDDEN, body
+
+ r = client.post("/api/auth/api-keys/", {"name": "x", "project": str(own.id)}, format="json")
+ assert r.status_code == status.HTTP_201_CREATED
+ assert r.data["scope"]["resourceIds"] == [str(own.id)]
+ assert APIToken.objects.filter(user=user).count() == 2
+
+
+def test_read_only_api_key_cannot_write():
+ user, project = make_user(), make_project()
+ ProjectMembership.objects.create(user=user, project=project)
+ raw, _ = APIToken.create_for_user(user, project=project, permission=["read"])
+ client = APIClient()
+ client.credentials(HTTP_X_API_KEY=raw)
+
+ assert client.get(f"/api/projects/{project.id}/").status_code == status.HTTP_200_OK
+ r = client.patch(f"/api/projects/{project.id}/", {"name": "renamed"}, format="json")
+ assert r.status_code == status.HTTP_403_FORBIDDEN
+ project.refresh_from_db()
+ assert project.name != "renamed"
+
+
+def test_api_key_mints_only_permissions_it_holds():
+ user, project = make_user(), make_project()
+ ProjectMembership.objects.create(user=user, project=project)
+ raw, _ = APIToken.create_for_user(user, project=project, permission=["write"])
+ client = APIClient()
+ client.credentials(HTTP_X_API_KEY=raw)
+
+ wider = client.post("/api/auth/api-keys/", {"project": str(project.id)}, format="json")
+ assert wider.status_code == status.HTTP_403_FORBIDDEN
+
+ same = {
+ "scope": {"scope": "project", "resourceIds": [str(project.id)], "permission": ["write"]}
+ }
+ r = client.post("/api/auth/api-keys/", same, format="json")
+ assert r.status_code == status.HTTP_201_CREATED
+ assert r.data["scope"]["permission"] == ["write"]
+
+
def test_api_key_current_returns_scope():
user, project = make_user(), make_project()
ProjectMembership.objects.create(user=user, project=project)