API Documentation

This document provides comprehensive details of the Konarr REST API. The API serves both the web UI and external integrations, with separate authentication for users and agents.

API Implementation: The REST API is implemented using the Rocket framework. All API routes are defined in the server/src/api directory.

Base URL and Versioning

Base URL: http://<konarr-host>:9000/api

Current Version: The API is currently unversioned. Future versions will include version paths.

Content Type: All endpoints expect and return application/json unless otherwise specified.

Authentication

Konarr supports two authentication methods: Agent tokens for automated tools and Session-based authentication for web users.

Agent Authentication

Agents authenticate using a Bearer token in the Authorization header:

curl -H "Authorization: Bearer <AGENT_TOKEN>" \
  http://localhost:9000/api/projects

The agent token is generated by the server and stored as agent.key in the ServerSettings table. You can retrieve it from the admin panel (Settings page) or by querying the database directly.

Key Points:

  • Agent tokens grant access to specific endpoints for uploading snapshots and creating projects
  • Token validation checks a cached value first, then falls back to database lookup (implemented in authentication guards)
  • Agents are identified as the konarr-agent user internally

Session Authentication

Web UI users authenticate via session cookies. Sessions are managed automatically by the frontend and use HTTP-only cookies (x-konarr-token) for security.

Authentication Endpoints (implementation):

  • Login: POST /api/auth/login
  • Logout: POST /api/auth/logout
  • Registration: POST /api/auth/register

Sessions are validated on each request and cached in memory for performance. Users can be assigned Admin or User roles (user model).

Admin Authentication

Admin-only endpoints require both:

  1. Valid session authentication
  2. User role must be Admin

The first registered user automatically receives the Admin role.

Quick Reference

Endpoint Summary

Base & Health Endpoints

EndpointMethodAuthenticationDescription
/api/GETOptionalServer status and statistics
/api/healthGETNoneHealth check

Authentication Endpoints

EndpointMethodAuthenticationDescription
/api/auth/loginPOSTNoneUser login
/api/auth/logoutPOSTSessionUser logout
/api/auth/registerPOSTNoneUser registration

Project Endpoints

(implementation)

EndpointMethodAuthenticationDescription
/api/projectsGETSession/AgentList projects
/api/projectsPOSTSession/AgentCreate project
/api/projects/{id}GETSessionGet project details
/api/projects/{id}PATCHSessionUpdate project
/api/projects/{id}DELETEAdminArchive project

Snapshot Endpoints

(implementation)

EndpointMethodAuthenticationDescription
/api/snapshotsGETSessionList snapshots
/api/snapshotsPOSTSessionCreate snapshot
/api/snapshots/{id}GETSessionGet snapshot details
/api/snapshots/{id}/bomPOSTSessionUpload SBOM
/api/snapshots/{id}/metadataPATCHSessionUpdate metadata
/api/snapshots/{id}/dependenciesGETSessionList snapshot dependencies
/api/snapshots/{id}/alertsGETSessionList snapshot alerts

Dependency Endpoints

(implementation)

EndpointMethodAuthenticationDescription
/api/dependenciesGETSessionList dependencies
/api/dependencies/{id}GETSessionGet dependency details

Security Alert Endpoints

(implementation)

EndpointMethodAuthenticationDescription
/api/securityGETSessionList security alerts
/api/security/{id}GETSessionGet alert details

User Management Endpoints

(implementation)

EndpointMethodAuthenticationDescription
/api/user/whoamiGETSessionGet current user
/api/user/passwordPATCHSessionUpdate password
/api/user/sessionsGETSessionList user sessions
/api/user/sessions/{id}DELETESessionRevoke session

Admin Endpoints

(implementation)

EndpointMethodAuthenticationDescription
/api/adminGETAdminGet admin settings
/api/adminPATCHAdminUpdate settings
/api/admin/usersGETAdminList all users
/api/admin/users/{id}PATCHAdminUpdate user

WebSocket Endpoint

(implementation)

EndpointMethodAuthenticationDescription
/api/ws?agentGET (WebSocket)SessionAgent status monitoring

Core Endpoints

Base Information

GET /api/ (implementation)

  • Description: Server status, configuration, and summary statistics
  • Authentication: Optional (returns more data when authenticated)
  • Response: Server version, commit, configuration, and statistics

Response Fields:

FieldTypeDescription
versionstringKonarr version number
commitstringGit commit SHA of the build
config.initialisedbooleanWhether the server has been initialized
config.registrationbooleanWhether new user registration is enabled
userobjectCurrent user details (authenticated only)
projectsobjectProject statistics summary (authenticated only)
dependenciesobjectDependency statistics summary (authenticated only)
securityobjectSecurity alerts summary (authenticated only)
agentobjectAgent configuration (agent authentication only)
# Unauthenticated request
curl http://localhost:9000/api/

# Authenticated request with session
curl -H "Cookie: x-konarr-token=<token>" http://localhost:9000/api/

Health Check

GET /api/health (implementation)

  • Description: Simple health check endpoint
  • Authentication: None required
  • Response: Basic status message and database connectivity check
curl http://localhost:9000/api/health

Response:

{
  "status": "ok",
  "message": "Konarr is running"
}

Projects

GET /api/projects

  • Description: List all active (non-archived) projects
  • Authentication: Session or Agent
  • Query Parameters:
ParameterTypeDescriptionDefault
pageintegerPage number for pagination (min 1)0
limitintegerResults per page (min 1, max 100)25
searchstringSearch projects by title-
typestringFilter by project type (or "all" for all types)-
topbooleanFetch only top-level projects (no parent)false
parentsbooleanFetch only parent projectsfalse
  • Response: Array of project objects with metadata

POST /api/projects

  • Description: Create a new project
  • Authentication: Session or Agent
  • Request Body:
FieldTypeRequiredDescription
namestringYesProject name (used as identifier)
typestringYesProject type (container, server, etc.)
descriptionstringNoOptional project description
parentintegerNoParent project ID (for nested projects)

GET /api/projects/{id}

  • Description: Get specific project details with latest snapshot and children
  • Authentication: Session
  • Response: Project details including children, latest snapshot, and security summary

PATCH /api/projects/{id}

  • Description: Update project details
  • Authentication: Session
  • Request Body (all fields optional):
FieldTypeDescription
titlestringDisplay title for the project
typestringProject type
descriptionstringProject description (empty string to clear)
parentintegerParent project ID

DELETE /api/projects/{id}

  • Description: Archive a project (soft delete)
  • Authentication: Admin session required
  • Response: Archived project details

Snapshots

GET /api/snapshots

  • Description: List all snapshots with pagination
  • Authentication: Session
  • Query Parameters:
ParameterTypeDescriptionDefault
pageintegerPage number for pagination0
limitintegerResults per page25

GET /api/snapshots/{id}

  • Description: Get specific snapshot details including metadata
  • Authentication: Session
  • Response: Snapshot metadata, dependencies count, and security summary

POST /api/snapshots

  • Description: Create a new empty snapshot
  • Authentication: Session
  • Request Body:
FieldTypeRequiredDescription
project_idintegerYesProject ID to associate snapshot with

POST /api/snapshots/{id}/bom

  • Description: Upload SBOM data to an existing snapshot
  • Authentication: Session
  • Content-Type: application/json (CycloneDX format)
  • Max Size: 10 MB
  • Response: Updated snapshot details
  • Note: Automatically triggers SBOM processing task

PATCH /api/snapshots/{id}/metadata

  • Description: Update snapshot metadata
  • Authentication: Session
  • Request Body: JSON object with key-value pairs of metadata to update
  • Note: Empty values are ignored; valid keys must match SnapshotMetadataKey enum

GET /api/snapshots/{id}/dependencies

  • Description: List dependencies for a specific snapshot
  • Authentication: Session
  • Query Parameters:
ParameterTypeDescription
searchstringSearch term for component names
pageintegerPage number for pagination
limitintegerResults per page

GET /api/snapshots/{id}/alerts

  • Description: List security alerts for a specific snapshot
  • Authentication: Session
  • Query Parameters:
ParameterTypeDescription
searchstringSearch term for alert names or CVE IDs
severitystringFilter by severity (critical, high, medium, low, etc.)
pageintegerPage number for pagination
limitintegerResults per page

Dependencies

GET /api/dependencies

  • Description: Search and list all dependencies (components)
  • Authentication: Session
  • Query Parameters:
ParameterTypeDescription
searchstringSearch term for component names
deptypestringFilter by component type (library, application, framework, etc.)
topbooleanGet top dependencies by usage
pageintegerPage number for pagination
limitintegerResults per page

GET /api/dependencies/{id}

  • Description: Get specific dependency details
  • Authentication: Session
  • Query Parameters:
ParameterTypeDescription
snapshotintegerGet dependency details for specific snapshot context
  • Response: Component details, versions across projects, and associated projects (when no snapshot specified)

Security Alerts

GET /api/security

  • Description: List security alerts and vulnerabilities
  • Authentication: Session
  • Query Parameters:
ParameterTypeDescription
pageintegerPage number for pagination
limitintegerNumber of results per page
searchstringSearch term for alert names or CVE IDs
statestringFilter by alert state (defaults to state check)
severitystringFilter by severity level (critical, high, medium, low, informational, malware, unmaintained, unknown)

GET /api/security/{id}

  • Description: Get specific security alert details
  • Authentication: Session
  • Response: Alert details including advisory information, affected dependency with full details, and associated snapshot

User Profile

GET /api/user/whoami

  • Description: Get current authenticated user's profile
  • Authentication: Session required
  • Response: User details including username, role, state, creation date, and last login

PATCH /api/user/password

  • Description: Update current user's password
  • Authentication: Session required
  • Request Body:
FieldTypeRequiredDescription
current_passwordstringYesCurrent password for verification
new_passwordstringYesNew password (min 12 characters)
new_password_confirmstringYesConfirmation of new password

GET /api/user/sessions

  • Description: List active sessions for the current user
  • Authentication: Session required
  • Response: Array of session summaries with ID, creation time, last accessed time, and state

DELETE /api/user/sessions/{id}

  • Description: Revoke a specific session
  • Authentication: Session required
  • Note: Can only revoke sessions belonging to the current user

Administration

GET /api/admin

  • Description: Administrative settings, statistics, and user list
  • Authentication: Admin session required
  • Response: Server settings, project statistics, user statistics, and list of all users

Response Fields:

FieldTypeDescription
settingsobjectKey-value pairs of all server settings
project_statsobjectTotal, inactive, and archived project counts
user_statsobjectTotal, active, and inactive user counts
usersarrayList of all users with summary information

PATCH /api/admin

  • Description: Update server settings
  • Authentication: Admin session required
  • Request Body: JSON object with setting names as keys and new values as strings
  • Note: Only Toggle, Regenerate, and SetString setting types can be updated
  • Special Actions: Some settings trigger background tasks (e.g., security.rescan, security.advisories.pull)

GET /api/admin/users

  • Description: List all users
  • Authentication: Admin session required
  • Response: Array of user summaries (ID, username, role, state, creation date)

PATCH /api/admin/users/{id}

  • Description: Update user role or state
  • Authentication: Admin session required
  • Request Body (all fields optional):
FieldTypeDescription
rolestringUser role (admin or user)
statestringUser state (active or disabled)
  • Note: Cannot modify user ID 1 (default admin); disabling a user logs them out

WebSocket

GET /api/ws?agent

  • Description: WebSocket connection for agent status monitoring
  • Authentication: Session required
  • Protocol: WebSocket
  • Purpose: Allows agents to report online/offline status for projects

Message Format:

{
  "project": 123
}

When a client connects and sends a project ID, the snapshot for that project is marked as "online". When the connection closes, it's marked as "offline".

Authentication API Details

Login

POST /api/auth/login

  • Description: Authenticate a user and create a session
  • Authentication: None required
  • Rate Limit: Yes (using RateLimit guard)
  • Request Body:
FieldTypeRequiredDescription
usernamestringYesUsername
passwordstringYesPassword
  • Response: Login status and reason (if failed)
  • Side Effect: Sets x-konarr-token private cookie on success

Response:

{
  "status": "success"
}

Or on failure:

{
  "status": "failed",
  "reason": "Invalid credentials"
}

Logout

POST /api/auth/logout

  • Description: Terminate the current session
  • Authentication: Session required
  • Response: Logout status
  • Side Effect: Removes x-konarr-token cookie and invalidates session

Register

POST /api/auth/register

  • Description: Register a new user account
  • Authentication: None required (registration must be enabled)
  • Rate Limit: Yes (using RateLimit guard)
  • Request Body:
FieldTypeRequiredDescription
usernamestringYesDesired username
passwordstringYesPassword
password_confirmstringYesPassword confirmation (must match)
  • Response: Registration status and reason (if failed)
  • Note: First registered user becomes Admin; subsequent users are regular Users

Data Models

Project Object

{
  "id": 1,
  "name": "my-application",
  "title": "my-application",
  "type": "container",
  "description": "Production web application",
  "status": true,
  "parent": null,
  "createdAt": "2024-01-01T00:00:00Z",
  "snapshot": {
    "id": 15,
    "status": "completed",
    "createdAt": "2024-01-15T12:00:00Z",
    "dependencies": 245,
    "security": {
      "total": 12,
      "critical": 2,
      "high": 5,
      "medium": 3,
      "low": 2
    }
  },
  "snapshots": 15,
  "security": {
    "total": 12,
    "critical": 2,
    "high": 5,
    "medium": 3,
    "low": 2
  },
  "children": []
}

Fields:

FieldTypeDescription
idintegerUnique project identifier
namestringProject name (identifier)
titlestringDisplay title for project
typestringProject type (container, server, etc.)
descriptionstringOptional project description
statusbooleanOnline/offline status from latest snapshot metadata
parentintegerParent project ID (null for top-level)
createdAtstringISO 8601 timestamp of creation
snapshotobjectLatest snapshot summary
snapshotsintegerTotal snapshot count
securityobjectSecurity summary from latest snapshot
childrenarrayChild projects (nested structure)

Snapshot Object

{
  "id": 1,
  "status": "completed",
  "error": null,
  "createdAt": "2024-01-01T00:00:00Z",
  "updatedAt": "2024-01-01T00:05:00Z",
  "dependencies": 245,
  "security": {
    "total": 12,
    "critical": 2,
    "high": 5,
    "medium": 3,
    "low": 2,
    "informational": 0,
    "unmaintained": 0,
    "malware": 0,
    "unknown": 0
  },
  "metadata": {
    "image": "nginx:1.21",
    "version": "1.21.0",
    "status": "online"
  }
}

Fields:

FieldTypeDescription
idintegerUnique snapshot identifier
statusstringProcessing status (pending, processing, completed, failed)
errorstringError message if processing failed
createdAtstringISO 8601 timestamp of creation
updatedAtstringISO 8601 timestamp of last update
dependenciesintegerCount of dependencies in snapshot
securityobjectSecurity summary with severity breakdown
metadataobjectKey-value pairs of snapshot metadata

Dependency Object

{
  "id": 1,
  "type": "library",
  "manager": "npm",
  "name": "@types/node",
  "namespace": "@types",
  "version": "18.15.0",
  "purl": "pkg:npm/%40types/node@18.15.0",
  "versions": ["18.15.0", "18.14.0"],
  "projects": [
    {
      "id": 1,
      "name": "my-application",
      "title": "my-application"
    }
  ]
}

Fields:

FieldTypeDescription
idintegerUnique component identifier
typestringComponent type (library, application, framework, etc.)
managerstringPackage manager (npm, cargo, deb, etc.)
namestringComponent name
namespacestringOptional namespace (e.g., @types for npm)
versionstringSpecific version (context-dependent)
purlstringPackage URL (PURL) identifier
versionsarrayAll versions found across projects
projectsarrayAssociated projects (omitted in snapshot context)

Alert Object

{
  "id": 1,
  "name": "CVE-2024-1234",
  "severity": "high",
  "description": "Buffer overflow vulnerability...",
  "url": "https://nvd.nist.gov/vuln/detail/CVE-2024-1234",
  "dependency": {
    "id": 42,
    "type": "library",
    "manager": "npm",
    "name": "vulnerable-package",
    "version": "1.0.0"
  }
}

Fields:

FieldTypeDescription
idintegerUnique alert identifier
namestringAlert name (often CVE ID)
severitystringSeverity level (critical, high, medium, low, informational, unmaintained, malware, unknown)
descriptionstringDetailed description of the vulnerability
urlstringReference URL for more information
dependencyobjectAffected dependency details

SBOM Upload Format

Konarr accepts SBOMs in CycloneDX format (version 1.5 or 1.6). Upload SBOMs to the POST /api/snapshots/{id}/bom endpoint.

Example CycloneDX SBOM:

{
  "bomFormat": "CycloneDX",
  "specVersion": "1.6",
  "version": 1,
  "metadata": {
    "timestamp": "2024-01-01T00:00:00Z",
    "tools": [
      {
        "vendor": "anchore",
        "name": "syft",
        "version": "v0.96.0"
      }
    ],
    "component": {
      "type": "container",
      "name": "nginx",
      "version": "1.21"
    }
  },
  "components": [
    {
      "type": "library",
      "name": "openssl",
      "version": "1.1.1",
      "purl": "pkg:deb/debian/openssl@1.1.1"
    }
  ]
}

Supported Fields:

  • bomFormat: Must be "CycloneDX"
  • specVersion: "1.5" or "1.6"
  • metadata.component: Main component (container image, application, etc.)
  • components: Array of dependency components with PURL identifiers

After uploading, Konarr automatically processes the SBOM to extract dependencies and match them against security advisories.

Error Responses

API errors return consistent JSON responses with HTTP status codes:

{
  "message": "Project with ID 999 not found",
  "details": "Additional context about the error",
  "status": 404
}

HTTP Status Codes:

Status CodeDescription
401 UnauthorizedMissing or invalid authentication token/session
404 Not FoundRequested resource doesn't exist
429 Too Many RequestsRate limit exceeded
500 Internal Server ErrorServer-side error occurred

Common Error Scenarios:

  • Authentication Errors: Returned when Authorization header or session cookie is missing/invalid
  • Not Found: Returned when accessing non-existent projects, snapshots, or other resources
  • Unauthorized (Admin): Returned when non-admin users attempt admin-only operations
  • Validation Errors: Returned via KonarrError when request data is invalid

Rate Limiting

Rate limiting is applied to authentication endpoints to prevent abuse:

  • Login endpoint: Rate limited (specific limit configured via RocketGovernor)
  • Registration endpoint: Rate limited (specific limit configured via RocketGovernor)
  • Other endpoints: No explicit rate limiting (protected by authentication)

Rate limiting uses the rocket-governor crate with a custom RateLimit guard.

Integration Examples

Using the API with curl

Creating a snapshot and uploading an SBOM:

# 1. Login and get session cookie
curl -c cookies.txt -X POST http://localhost:9000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": "yourpassword"}'

# 2. Create a snapshot for a project
curl -b cookies.txt -X POST http://localhost:9000/api/snapshots \
  -H "Content-Type: application/json" \
  -d '{"project_id": 1}'

# 3. Upload SBOM to the snapshot
curl -b cookies.txt -X POST http://localhost:9000/api/snapshots/123/bom \
  -H "Content-Type: application/json" \
  -d @sbom.json

Agent authentication:

# Get agent token from admin panel, then use it
export AGENT_TOKEN="your-agent-token-here"

# List projects as agent
curl -H "Authorization: Bearer $AGENT_TOKEN" \
  http://localhost:9000/api/projects

# Upload SBOM as agent
curl -H "Authorization: Bearer $AGENT_TOKEN" \
  -X POST http://localhost:9000/api/snapshots/123/bom \
  -H "Content-Type: application/json" \
  -d @sbom.json

Python Example

import requests

class KonarrClient:
    def __init__(self, base_url, agent_token=None):
        self.base_url = base_url
        self.session = requests.Session()
        if agent_token:
            self.session.headers['Authorization'] = f'Bearer {agent_token}'
    
    def login(self, username, password):
        response = self.session.post(
            f'{self.base_url}/api/auth/login',
            json={'username': username, 'password': password}
        )
        return response.json()
    
    def get_projects(self):
        response = self.session.get(f'{self.base_url}/api/projects')
        return response.json()
    
    def upload_sbom(self, snapshot_id, sbom_data):
        response = self.session.post(
            f'{self.base_url}/api/snapshots/{snapshot_id}/bom',
            json=sbom_data
        )
        return response.json()

# Usage
client = KonarrClient('http://localhost:9000')
client.login('admin', 'password')
projects = client.get_projects()

For CLI-based interaction with Konarr, see the Agent Configuration documentation.