diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c0c674..caaf633 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,14 @@ trace, study, receipt, API and database schema versions. ### Added +- Project API keys can be listed and revoked. Admin routes + `GET /v1/api-keys?project_id=` and `DELETE /v1/api-keys/{prefix}?project_id=`, + `AgentLoopClient.list_api_keys` / `revoke_api_key`, and the CLI commands + `list-api-keys`, `revoke-api-key`, `remote-list-api-keys` and + `remote-revoke-api-key` show prefixes and usage times, never key values. A + revoked key is rejected immediately, and project-mode dashboard sessions + re-check their key every minute. Shared dashboards no longer offer the demo + generators that write files on the host. - Shared dashboards can sign users in by project. With `AGENTLOOP_DASHBOARD_REQUIRE_KEY=true`, the dashboard asks for a project API key, verifies it like the HTTP API, and shows only that project; the project diff --git a/agentloop/cli.py b/agentloop/cli.py index 5137d27..175811f 100644 --- a/agentloop/cli.py +++ b/agentloop/cli.py @@ -988,6 +988,32 @@ def create_api_key(project_id: str = "default", name: str = "default") -> None: console.print(key["api_key"]) +@app.command("list-api-keys") +def list_api_keys(project_id: str = "default") -> None: + """List a project's API key prefixes and last use; key values are never shown.""" + console.print_json( + data={"project_id": project_id, "api_keys": get_store().list_api_keys(project_id)} + ) + + +@app.command("revoke-api-key") +def revoke_api_key( + prefix: str = typer.Option(..., help="First 10 characters of the key, as listed."), + project_id: str = "default", +) -> None: + """Revoke a project's API key; it stops working immediately.""" + try: + revoked = get_store().revoke_api_key(project_id, prefix) + except ValueError as exc: + raise typer.BadParameter(str(exc)) from exc + if not revoked: + console.print(f"No API key with prefix {prefix} in project {project_id}.", markup=False) + raise typer.Exit(1) + console.print( + f"Revoked {revoked} API key(s) with prefix {prefix} in project {project_id}.", markup=False + ) + + @app.command("store-trace") def store_trace( path: Path = Path("runs/research_agent_baseline.json"), @@ -1333,6 +1359,37 @@ def remote_create_api_key( console.print(key["api_key"]) +@app.command("remote-list-api-keys") +def remote_list_api_keys( + project_id: str = "default", + api_url: str = typer.Option("http://127.0.0.1:8000", help="AgentLoop API base URL."), + admin_api_key: str | None = typer.Option( + None, help="Admin API key. Defaults to AGENTLOOP_ADMIN_API_KEY." + ), +) -> None: + """List a project's API key prefixes on a remote server.""" + client = _remote_admin_client(api_url, admin_api_key) + console.print_json(data=client.list_api_keys(project_id)) + + +@app.command("remote-revoke-api-key") +def remote_revoke_api_key( + prefix: str = typer.Option(..., help="First 10 characters of the key, as listed."), + project_id: str = "default", + api_url: str = typer.Option("http://127.0.0.1:8000", help="AgentLoop API base URL."), + admin_api_key: str | None = typer.Option( + None, help="Admin API key. Defaults to AGENTLOOP_ADMIN_API_KEY." + ), +) -> None: + """Revoke a project's API key on a remote server.""" + client = _remote_admin_client(api_url, admin_api_key) + result = client.revoke_api_key(project_id, prefix) + console.print( + f"Revoked {result['revoked']} API key(s) with prefix {prefix} in project {project_id}.", + markup=False, + ) + + @app.command() def demo( kind: str = typer.Option("baseline", help="baseline, optimized, langgraph, or proof"), diff --git a/agentloop/client.py b/agentloop/client.py index 8b1ec9e..9ea79f6 100644 --- a/agentloop/client.py +++ b/agentloop/client.py @@ -59,6 +59,25 @@ def create_api_key(self, project_id: str = "default", name: str = "default") -> credential_scope="admin", ) + def list_api_keys(self, project_id: str) -> dict[str, Any]: + """List a project's key prefixes, names and usage times (admin key required).""" + return self._request( + "GET", + "/api-keys?" + urllib.parse.urlencode({"project_id": project_id}), + credential_scope="admin", + ) + + def revoke_api_key(self, project_id: str, prefix: str) -> dict[str, Any]: + """Revoke a project's key by its prefix (admin key required).""" + return self._request( + "DELETE", + "/api-keys/" + + urllib.parse.quote(prefix, safe="") + + "?" + + urllib.parse.urlencode({"project_id": project_id}), + credential_scope="admin", + ) + def upload_trace(self, trace: AgentTrace | str | Path | dict[str, Any]) -> dict[str, Any]: if isinstance(trace, AgentTrace): payload = trace.to_dict() diff --git a/agentloop/server.py b/agentloop/server.py index 73cab71..7763689 100644 --- a/agentloop/server.py +++ b/agentloop/server.py @@ -173,6 +173,33 @@ def create_api_key( return db.create_api_key(project_id=payload.project_id, name=payload.name) +@versioned.get("/api-keys") +def list_api_keys( + project_id: str = Query(min_length=1), + _: None = Depends(resolve_admin), + db: TraceStore = Depends(store), +) -> dict[str, Any]: + """List a project's key prefixes and usage times; never the keys themselves.""" + return {"project_id": project_id, "api_keys": db.list_api_keys(project_id)} + + +@versioned.delete("/api-keys/{prefix}") +def revoke_api_key( + prefix: str, + project_id: str = Query(min_length=1), + _: None = Depends(resolve_admin), + db: TraceStore = Depends(store), +) -> dict[str, Any]: + """Revoke a project's key by its prefix; it stops working immediately.""" + try: + revoked = db.revoke_api_key(project_id, prefix) + except ValueError as exc: + raise HTTPException(status_code=422, detail=str(exc)) from exc + if not revoked: + raise HTTPException(status_code=404, detail="no API key with that prefix in this project") + return {"project_id": project_id, "prefix": prefix, "revoked": revoked} + + @versioned.post("/traces") @legacy.post("/traces") def ingest_trace( diff --git a/agentloop/store.py b/agentloop/store.py index 65c3b12..32f14c3 100644 --- a/agentloop/store.py +++ b/agentloop/store.py @@ -105,6 +105,10 @@ def create_api_key(self, project_id: str, name: str) -> dict[str, Any]: ... def verify_api_key(self, api_key: str) -> dict[str, Any] | None: ... + def list_api_keys(self, project_id: str) -> list[dict[str, Any]]: ... + + def revoke_api_key(self, project_id: str, prefix: str) -> int: ... + def save_trace(self, trace: AgentTrace, project_id: str = "default") -> None: ... def list_traces(self, project_id: str | None = None) -> list[dict[str, Any]]: ... @@ -192,6 +196,19 @@ def _decode_hash_bytes(value: str) -> bytes: return base64.b64decode(padded.encode("ascii"), altchars=b"-_", validate=True) +def _timestamp_text(value: Any) -> str | None: + if value is None: + return None + return value.isoformat() if hasattr(value, "isoformat") else str(value) + + +def _require_key_prefix(prefix: Any) -> None: + if not isinstance(prefix, str) or len(prefix) != _API_KEY_PREFIX_LENGTH: + raise ValueError( + f"API key prefix must be the first {_API_KEY_PREFIX_LENGTH} characters of the key" + ) + + def new_api_key() -> str: return "al_" + secrets.token_urlsafe(32) @@ -479,6 +496,37 @@ def verify_api_key(self, api_key: str) -> dict[str, Any] | None: ) return {key: row[key] for key in ("project_id", "name", "prefix")} + def list_api_keys(self, project_id: str) -> list[dict[str, Any]]: + """Key metadata for one project; key values and hashes are never returned.""" + self.init() + with self._connect() as conn: + rows = conn.execute( + "SELECT prefix, name, created_at, last_used_at FROM api_keys " + "WHERE project_id = ? ORDER BY created_at, prefix", + (project_id,), + ).fetchall() + return [ + { + "project_id": project_id, + "prefix": row["prefix"], + "name": row["name"], + "created_at": _timestamp_text(row["created_at"]), + "last_used_at": _timestamp_text(row["last_used_at"]), + } + for row in rows + ] + + def revoke_api_key(self, project_id: str, prefix: str) -> int: + """Delete a project's keys with this prefix; returns how many were revoked.""" + _require_key_prefix(prefix) + self.init() + with self._connect() as conn: + cursor = conn.execute( + "DELETE FROM api_keys WHERE project_id = ? AND prefix = ?", + (project_id, prefix), + ) + return int(cursor.rowcount or 0) + def _upsert_trace( self, conn: sqlite3.Connection, trace: AgentTrace, project_id: str ) -> dict[str, Any]: @@ -942,6 +990,37 @@ def verify_api_key(self, api_key: str) -> dict[str, Any] | None: ) return {"project_id": row[1], "name": row[2], "prefix": row[3]} + def list_api_keys(self, project_id: str) -> list[dict[str, Any]]: + """Key metadata for one project; key values and hashes are never returned.""" + self.init() + with self._connect() as conn: + rows = conn.execute( + "SELECT prefix, name, created_at, last_used_at FROM api_keys " + "WHERE project_id = %s ORDER BY created_at, prefix", + (project_id,), + ).fetchall() + return [ + { + "project_id": project_id, + "prefix": row[0], + "name": row[1], + "created_at": _timestamp_text(row[2]), + "last_used_at": _timestamp_text(row[3]), + } + for row in rows + ] + + def revoke_api_key(self, project_id: str, prefix: str) -> int: + """Delete a project's keys with this prefix; returns how many were revoked.""" + _require_key_prefix(prefix) + self.init() + with self._connect() as conn: + cursor = conn.execute( + "DELETE FROM api_keys WHERE project_id = %s AND prefix = %s", + (project_id, prefix), + ) + return int(cursor.rowcount or 0) + def _upsert_trace(self, conn, trace: AgentTrace, project_id: str) -> dict[str, Any]: report = trace.report() cost_status, priced_calls, unavailable_calls = _report_cost_completeness(report) diff --git a/dashboard/access.py b/dashboard/access.py index 320dcde..7a85e23 100644 --- a/dashboard/access.py +++ b/dashboard/access.py @@ -17,6 +17,8 @@ PROJECT_HIDDEN_PAGES = frozenset({"API Keys", "Patch Plan"}) MAX_FAILURES = 5 LOCKOUT_SECONDS = 60.0 +# A revoked key stops working in open dashboard sessions within this time. +RECHECK_SECONDS = 60.0 def require_project_key() -> bool: @@ -63,9 +65,39 @@ def sign_in(store, api_key: str, state, now: float | None = None) -> str | None: state["signin_failures"] = 0 state["signed_in_project"] = str(record["project_id"]) state["signed_in_key_prefix"] = str(record.get("prefix") or "") + # Held only in this server-side session so the key can be re-verified. + state["signed_in_key"] = key + state["signed_in_checked_at"] = now return state["signed_in_project"] +def session_valid(store, state, now: float | None = None) -> bool: + """Re-verify a signed-in session's key at most every ``RECHECK_SECONDS``. + + A key that was revoked, or that now belongs to another project, signs the + session out. + """ + now = time.monotonic() if now is None else now + project = state.get("signed_in_project") + key = state.get("signed_in_key") + if not project or not key: + sign_out(state) + return False + if now - float(state.get("signed_in_checked_at", float("-inf"))) < RECHECK_SECONDS: + return True + record = store.verify_api_key(key) + if record is None or str(record["project_id"]) != project: + sign_out(state) + return False + state["signed_in_checked_at"] = now + return True + + def sign_out(state) -> None: - for name in ("signed_in_project", "signed_in_key_prefix"): + for name in ( + "signed_in_project", + "signed_in_key_prefix", + "signed_in_key", + "signed_in_checked_at", + ): state.pop(name, None) diff --git a/dashboard/app.py b/dashboard/app.py index 4a4a50e..018d877 100644 --- a/dashboard/app.py +++ b/dashboard/app.py @@ -35,6 +35,7 @@ from dashboard.access import ( lockout_remaining, require_project_key, + session_valid, sign_in, sign_out, visible_pages, @@ -42,7 +43,14 @@ from dashboard.trace_upload import TraceUploadError, parse_uploaded_trace from dashboard.value_view import assumption_inputs, percentage, render_value_report except ModuleNotFoundError: - from access import lockout_remaining, require_project_key, sign_in, sign_out, visible_pages + from access import ( + lockout_remaining, + require_project_key, + session_valid, + sign_in, + sign_out, + visible_pages, + ) from trace_upload import TraceUploadError, parse_uploaded_trace from value_view import assumption_inputs, percentage, render_value_report @@ -127,8 +135,14 @@ def render_gate_table(results: list[dict]) -> None: if project_mode: # A shared dashboard shows exactly one project: the one the API key belongs to. + if "signed_in_project" in st.session_state and not session_valid(store, st.session_state): + st.session_state["signin_notice"] = ( + "Your project API key was revoked or is no longer valid. Sign in again." + ) if "signed_in_project" not in st.session_state: st.title("AgentLoop Dashboard") + if notice := st.session_state.pop("signin_notice", None): + st.warning(notice) st.subheader("Sign in to your project") st.caption( "Enter a project API key. The dashboard shows only the traces and findings " @@ -880,16 +894,19 @@ def render_gate_table(results: list[dict]) -> None: ) elif page == "Ingest": - st.subheader("Generate or upload traces") - col_a, col_b, col_c, col_d = st.columns(4) + # Demo generators write files into the dashboard host's shared runs directory, + # so a shared dashboard offers only uploads into the signed-in project. + st.subheader("Upload traces" if project_mode else "Generate or upload traces") generated_path: Path | None = None - if col_a.button("Generate baseline"): + if not project_mode: + col_a, col_b, col_c, col_d = st.columns(4) + if not project_mode and col_a.button("Generate baseline"): generated_path = run_baseline(runs_dir) - if col_b.button("Generate optimized"): + if not project_mode and col_b.button("Generate optimized"): generated_path = run_optimized(runs_dir) - if col_c.button("Generate LangGraph-style"): + if not project_mode and col_c.button("Generate LangGraph-style"): generated_path = run_langgraph_style(runs_dir) - if col_d.button("Generate all"): + if not project_mode and col_d.button("Generate all"): proof_baseline, proof_candidate = run_proof_pair(runs_dir) for path in [ run_baseline(runs_dir), @@ -901,7 +918,7 @@ def render_gate_table(results: list[dict]) -> None: store.save_trace(AgentTrace.from_json(path), project_id=project_id) st.success(f"Generated and stored all demo traces under project `{project_id}`") - if st.button("Generate proof demo pair"): + if not project_mode and st.button("Generate proof demo pair"): proof_baseline, proof_candidate = run_proof_pair(runs_dir) for path in [proof_baseline, proof_candidate]: store.save_trace(AgentTrace.from_json(path), project_id=project_id) diff --git a/docs/API_VERSIONING.md b/docs/API_VERSIONING.md index ec035a9..1ff7cda 100644 --- a/docs/API_VERSIONING.md +++ b/docs/API_VERSIONING.md @@ -31,6 +31,8 @@ for larger reports. `timeout_s` controls the underlying socket timeout. | Versioned route | Deprecated compatibility route | | --- | --- | | `POST /v1/api-keys` | `POST /api-keys` | +| `GET /v1/api-keys?project_id=...` | None (0.2.7 and newer) | +| `DELETE /v1/api-keys/{prefix}?project_id=...` | None (0.2.7 and newer) | | `GET/POST /v1/traces` | `GET/POST /traces` | | `GET /v1/traces/{run_id}/report` | `GET /traces/{run_id}/report` | | `GET /v1/traces/{run_id}/optimization` | `GET /traces/{run_id}/optimize` | diff --git a/docs/CLOUD_DEPLOY.md b/docs/CLOUD_DEPLOY.md index 4b08048..c9537a9 100644 --- a/docs/CLOUD_DEPLOY.md +++ b/docs/CLOUD_DEPLOY.md @@ -110,6 +110,21 @@ or from the TypeScript SDK with Sign in to the dashboard with the same key to see that project's traces. Each team can only see its own project; there is no project switcher. +### Revoke a key + +If a key leaks or a pipeline is retired, list the project's keys and revoke the +one by its prefix (the first 10 characters of the key): + +```bash +export AGENTLOOP_ADMIN_API_KEY=... +agentloop remote-list-api-keys --project-id my-team --api-url https://agentloop-api.example.com +agentloop remote-revoke-api-key --project-id my-team --prefix al_AbCdEfG \ + --api-url https://agentloop-api.example.com +``` + +The API rejects the key immediately, and dashboard sessions signed in with it +end within a minute. + ### Upgrade and back up Back up the database, change `AGENTLOOP_IMAGE` to the new version, then @@ -198,7 +213,8 @@ behind an authenticating ingress. ## Security checklist - Require API keys (`AGENTLOOP_REQUIRE_API_KEY=true`) and keep the admin key - out of clients; give each team or pipeline its own project key. + out of clients; give each team or pipeline its own project key, and revoke + keys that leak or are no longer used. - Serve only HTTPS, never expose the dashboard without a login, and keep project sign-in enabled so teams only see their own traces. - Keep Postgres off the public internet and back it up. diff --git a/docs/DASHBOARD.md b/docs/DASHBOARD.md index 912c507..6b85b46 100644 --- a/docs/DASHBOARD.md +++ b/docs/DASHBOARD.md @@ -79,10 +79,14 @@ key, checks it the same way the HTTP API does, and shows only the traces, findings and reports of the project that key belongs to. The free-text Project field is replaced by the signed-in project and a Sign out button. The `API Keys` page (creating keys is an administrator task) and the `Patch Plan` page (it -reads files on the dashboard host) are hidden. After five failed sign-ins in a -browser session, further attempts wait one minute. - -Create project keys with the API's admin key or `agentloop create-api-key`. +reads files on the dashboard host) are hidden, and the `Ingest` page offers only +uploads into the signed-in project, without the demo generators that write files +on the host. After five failed sign-ins in a browser session, further attempts +wait one minute. Open sessions re-check their key at least once a minute, so a +revoked key loses access within a minute. + +Create and revoke project keys with the API's admin key, or with +`agentloop create-api-key` and `agentloop revoke-api-key`. Without the setting, the dashboard keeps its local, single-user behaviour. ## Security boundaries diff --git a/docs/PRODUCTION.md b/docs/PRODUCTION.md index 4580301..84fb74a 100644 --- a/docs/PRODUCTION.md +++ b/docs/PRODUCTION.md @@ -40,12 +40,26 @@ PGPASSWORD= For file-backed secrets, set `AGENTLOOP_POSTGRES_PASSWORD_FILE` instead of `PGPASSWORD`. The file is read only when no complete database URL is configured. -`AGENTLOOP_ADMIN_API_KEY` protects hosted API-key creation. When API auth is enabled, +`AGENTLOOP_ADMIN_API_KEY` protects hosted API-key management. When API auth is enabled, `POST /v1/api-keys` returns `503` unless the admin secret is configured. +From 0.2.7, the admin key can also list a project's keys and revoke one by the +first 10 characters it starts with (its prefix). Listing returns prefixes, names +and creation and last-use times, never key values. A revoked key is rejected by +the API immediately and ends open dashboard sessions within a minute. + +```bash +uv run agentloop remote-list-api-keys --project-id acme --api-url https://agentloop-api.example.com +uv run agentloop remote-revoke-api-key --project-id acme --prefix al_AbCdEfG \ + --api-url https://agentloop-api.example.com +``` + +Both read the admin key from `AGENTLOOP_ADMIN_API_KEY` or `--admin-api-key`. With direct +database access, `agentloop list-api-keys` and `agentloop revoke-api-key` do the same. + The Python client's credential handling is endpoint-specific. `AgentLoopClient.from_env()` may load both credentials, but sends `X-AgentLoop-Key` only on ordinary project requests -and `X-AgentLoop-Admin-Key` only on `POST /v1/api-keys`; the headers are never sent together. +and `X-AgentLoop-Admin-Key` only on the `/v1/api-keys` routes; the headers are never sent together. Keep the admin secret in trusted management processes and do not use it for trace uploads, reports, findings, usage, health checks, or other ordinary API calls. diff --git a/tests/test_cli_store_commands.py b/tests/test_cli_store_commands.py index 6ca34ef..5d3b4fb 100644 --- a/tests/test_cli_store_commands.py +++ b/tests/test_cli_store_commands.py @@ -93,3 +93,32 @@ def test_update_finding_status_command_transitions_and_rejects_invalid( f for f in store.list_findings(project_id="cli-test") if f["finding_id"] == finding_id ) assert finding["status"] == "resolved" + + +def test_list_and_revoke_api_keys_from_the_cli(tmp_path, monkeypatch) -> None: + db_path = tmp_path / "keys.db" + monkeypatch.setenv("AGENTLOOP_STORE_BACKEND", "sqlite") + monkeypatch.setenv("AGENTLOOP_SQLITE_PATH", str(db_path)) + store = SQLiteTraceStore(path=str(db_path)) + created = store.create_api_key(project_id="acme", name="ci") + + listed = runner.invoke(app, ["list-api-keys", "--project-id", "acme"]) + assert listed.exit_code == 0, listed.output + assert created["prefix"] in listed.output + assert created["api_key"] not in listed.output + + missing = runner.invoke( + app, ["revoke-api-key", "--project-id", "other", "--prefix", created["prefix"]] + ) + assert missing.exit_code == 1 + assert store.verify_api_key(created["api_key"]) is not None + + bad = runner.invoke(app, ["revoke-api-key", "--project-id", "acme", "--prefix", "al_"]) + assert bad.exit_code == 2 + + revoked = runner.invoke( + app, ["revoke-api-key", "--project-id", "acme", "--prefix", created["prefix"]] + ) + assert revoked.exit_code == 0, revoked.output + assert "Revoked 1" in revoked.output + assert store.verify_api_key(created["api_key"]) is None diff --git a/tests/test_client.py b/tests/test_client.py index e5b7ba7..bd9d4b3 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -235,3 +235,37 @@ def test_client_from_env_routes_each_credential_to_its_scope(monkeypatch) -> Non assert "x-agentloop-admin-key" not in captured[0] assert captured[1]["x-agentloop-admin-key"] == "admin-secret" assert "x-agentloop-key" not in captured[1] + + +def test_client_lists_and_revokes_keys_with_only_the_admin_key(monkeypatch) -> None: + captured: list[tuple[str, str, dict[str, str]]] = [] + + class Response: + def __enter__(self): + return self + + def __exit__(self, *args): # type: ignore[no-untyped-def] + return None + + def read(self, size=-1) -> bytes: + return b"{}" + + def fake_urlopen(request, timeout): # type: ignore[no-untyped-def] + headers = {name.lower(): value for name, value in request.header_items()} + captured.append((request.get_method(), request.full_url, headers)) + return Response() + + monkeypatch.setattr("agentloop.client._open_request", fake_urlopen) + client = AgentLoopClient( + base_url="https://agentloop.example", api_key="project-secret", admin_api_key="admin" + ) + client.list_api_keys("team a") + client.revoke_api_key("team a", "al_ab/cd?e") + + assert [(method, url) for method, url, _ in captured] == [ + ("GET", "https://agentloop.example/v1/api-keys?project_id=team+a"), + ("DELETE", "https://agentloop.example/v1/api-keys/al_ab%2Fcd%3Fe?project_id=team+a"), + ] + for _, _, headers in captured: + assert headers["x-agentloop-admin-key"] == "admin" + assert "x-agentloop-key" not in headers diff --git a/tests/test_dashboard_project_access.py b/tests/test_dashboard_project_access.py index 55d46e4..a22bb5e 100644 --- a/tests/test_dashboard_project_access.py +++ b/tests/test_dashboard_project_access.py @@ -15,8 +15,10 @@ from dashboard.access import ( # noqa: E402 LOCKOUT_SECONDS, MAX_FAILURES, + RECHECK_SECONDS, lockout_remaining, require_project_key, + session_valid, sign_in, sign_out, visible_pages, @@ -146,3 +148,36 @@ def test_local_dashboard_keeps_the_free_project_field(tmp_path, monkeypatch): assert not app.exception assert [w.label for w in app.sidebar.text_input] == ["Project"] assert "API Keys" in app.sidebar.radio[0].options + + +def test_open_sessions_lose_access_after_their_key_is_revoked(tmp_path): + store = _store(tmp_path) + created = store.create_api_key(project_id="alpha", name="team") + state = {} + assert sign_in(store, created["api_key"], state, now=0.0) == "alpha" + assert session_valid(store, state, now=RECHECK_SECONDS - 1) + store.revoke_api_key("alpha", created["prefix"]) + # Within the recheck window the session continues; after it, it ends. + assert session_valid(store, state, now=RECHECK_SECONDS - 1) + assert not session_valid(store, state, now=RECHECK_SECONDS + 1) + assert "signed_in_project" not in state and "signed_in_key" not in state + + +def test_a_valid_session_is_rechecked_and_kept(tmp_path): + store = _store(tmp_path) + key = store.create_api_key(project_id="alpha", name="team")["api_key"] + state = {} + sign_in(store, key, state, now=0.0) + assert session_valid(store, state, now=RECHECK_SECONDS + 1) + assert state["signed_in_checked_at"] == RECHECK_SECONDS + 1 + assert not session_valid(store, {}, now=0.0) + + +def test_shared_ingest_page_offers_only_uploads(tmp_path, monkeypatch): + app, key = _app(tmp_path, monkeypatch, require_key=True) + _sign_in(app, key) + app.sidebar.radio[0].set_value("Ingest").run() + assert not app.exception + labels = [button.label for button in app.button] + assert not any(label.startswith("Generate") for label in labels) + assert app.file_uploader, "uploading into the signed-in project stays available" diff --git a/tests/test_server.py b/tests/test_server.py index c8af768..05d9a27 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -588,3 +588,38 @@ def test_update_finding_status_transition_lifecycle(monkeypatch, tmp_path: Path) assert conflict.status_code == 409 assert not_found.status_code == 404 assert bad_status.status_code == 400 + + +def test_admin_lists_and_revokes_project_api_keys(monkeypatch, tmp_path) -> None: + monkeypatch.setenv("AGENTLOOP_STORE_BACKEND", "sqlite") + monkeypatch.setenv("AGENTLOOP_SQLITE_PATH", str(tmp_path / "keys.db")) + monkeypatch.setenv("AGENTLOOP_REQUIRE_API_KEY", "true") + monkeypatch.setenv("AGENTLOOP_ADMIN_API_KEY", "admin-secret") + client = TestClient(app) + admin = {"X-AgentLoop-Admin-Key": "admin-secret"} + key = client.post( + "/v1/api-keys", json={"project_id": "acme", "name": "ci"}, headers=admin + ).json() + project = {"X-AgentLoop-Key": key["api_key"]} + assert client.get("/v1/traces", headers=project).status_code == 200 + + assert client.get("/v1/api-keys", params={"project_id": "acme"}).status_code == 401 + assert ( + client.get("/v1/api-keys", params={"project_id": "acme"}, headers=project).status_code + == 401 + ) + listed = client.get("/v1/api-keys", params={"project_id": "acme"}, headers=admin).json() + assert [item["prefix"] for item in listed["api_keys"]] == [key["prefix"]] + assert key["api_key"] not in str(listed) + + delete = f"/v1/api-keys/{key['prefix']}" + assert client.delete(delete, params={"project_id": "acme"}, headers=project).status_code == 401 + assert client.delete(delete, params={"project_id": "other"}, headers=admin).status_code == 404 + assert ( + client.delete("/v1/api-keys/al_", params={"project_id": "acme"}, headers=admin).status_code + == 422 + ) + revoked = client.delete(delete, params={"project_id": "acme"}, headers=admin) + assert revoked.status_code == 200 and revoked.json()["revoked"] == 1 + assert client.get("/v1/traces", headers=project).status_code == 401 + assert client.delete(delete, params={"project_id": "acme"}, headers=admin).status_code == 404 diff --git a/tests/test_store_contract.py b/tests/test_store_contract.py index f8b6084..705b741 100644 --- a/tests/test_store_contract.py +++ b/tests/test_store_contract.py @@ -212,6 +212,27 @@ def test_api_key_roundtrip(store): assert store.verify_api_key("al_wrong-key-entirely") is None +def test_api_keys_are_listed_without_secrets_and_revoked_per_project(store): + first = store.create_api_key(project_id="proj_a", name="ci") + second = store.create_api_key(project_id="proj_a", name="laptop") + other = store.create_api_key(project_id="proj_b", name="ci") + listed = store.list_api_keys("proj_a") + assert sorted(item["name"] for item in listed) == ["ci", "laptop"] + assert {item["prefix"] for item in listed} == {first["prefix"], second["prefix"]} + for item in listed: + assert set(item) == {"project_id", "prefix", "name", "created_at", "last_used_at"} + assert first["api_key"] not in str(item) + # Another project's key cannot be revoked through this project. + assert store.revoke_api_key("proj_a", other["prefix"]) == 0 + assert store.verify_api_key(other["api_key"]) is not None + assert store.revoke_api_key("proj_a", first["prefix"]) == 1 + assert store.verify_api_key(first["api_key"]) is None + assert store.verify_api_key(second["api_key"]) is not None + assert [item["name"] for item in store.list_api_keys("proj_a")] == ["laptop"] + with pytest.raises(ValueError, match="prefix"): + store.revoke_api_key("proj_a", "al_") + + # --- trace upsert / conflicts -------------------------------------------