Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
244 changes: 181 additions & 63 deletions .github/workflows/ci-config.md

Large diffs are not rendered by default.

40 changes: 27 additions & 13 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,12 @@ jobs:
- name: Create test databases
# The test harness uses isolated test DBs (devteam_test_db,
# devteam_test_api, devteam_test_spec, devteam_test_intake,
# devteam_test_pipeline, devteam_test_chat). The postgres service
# container only creates the default DB, so create the rest here.
# devteam_test_pipeline, devteam_test_chat, devteam_test_defaults).
# The postgres service container only creates the default DB, so
# create the rest here. devteam_test_chat is dedicated to the
# chat/streaming packages; devteam_test_defaults is dedicated to
# internal/settings/defaults to avoid truncate races with
# internal/db's shared devteam_test_db (see store_test.go:19).
run: |
for db in devteam_test_db devteam_test_api devteam_test_spec devteam_test_intake devteam_test_pipeline devteam_test_chat devteam_test_config devteam_test_defaults; do
PGPASSWORD=devteam psql -h localhost -U devteam -d devteam -c "CREATE DATABASE $db;" || true
Expand All @@ -90,24 +94,33 @@ jobs:
run: go build ./...

- name: Vet (feature packages)
# Scoped to the packages this feature and the prior feature extend.
# Scoped to the packages this feature and prior features extend.
# A full `go vet ./...` surfaces pre-existing unkeyed-field warnings
# in internal/stage/definitions.go that predate this feature and are
# out of scope to fix here (see team-practices evidence §3).
# Extension (stream-agent-output feature): added internal/role,
# internal/pipeline, internal/config — the packages the streaming
# refactor touches.
run: go vet ./internal/db/... ./internal/api/... ./internal/role/... ./internal/pipeline/... ./internal/config/...
# Covers: streaming (internal/role, internal/pipeline, internal/config)
# and settings-and-admin-ui (internal/repo, internal/settings,
# internal/config write path). internal/opencode is NOT in scope —
# the builder package is owned by the sibling feature
# multi-provider-llm-configuration (Q7 scope cut).
run: go vet ./internal/db/... ./internal/api/... ./internal/role/... ./internal/pipeline/... ./internal/repo/... ./internal/settings/... ./internal/config/...

- name: Unit tests — feature packages (per-bolt gate)
# The load-bearing gate command from team-practices P7/P8. Runs the
# packages the feature extends. Full `go test ./...` runs in the
# release job (backend-full).
# Extension (stream-agent-output feature): added internal/role
# (new streamer.go, rewritten tmux.go), internal/pipeline
# (stage_runner.go, session_manager.go), internal/config
# (new Streaming block).
run: go test ./internal/db/... ./internal/api/... ./internal/role/... ./internal/pipeline/... ./internal/config/... -count=1
# Streaming: internal/role, internal/pipeline, internal/config.
# Settings-and-admin-ui: internal/repo, internal/settings,
# internal/config (write path — U-CONFIG-01 linchpin, fails fast).
run: go test ./internal/db/... ./internal/api/... ./internal/role/... ./internal/pipeline/... ./internal/repo/... ./internal/config/... -count=1

- name: Race tests — concurrency-touching packages (QO-14)
# Binding per quality-report revision 2 §1.4 / QO-14: the
# concurrency-touching packages (repos flock, config atomic write,
# settings store, role batcher) must be -race clean. Runs in the
# backend job alongside the db/api unit gate so a race regression
# fails the fast gate, not just backend-full.
run: go test -race ./internal/role/... ./internal/pipeline/... ./internal/repo/... ./internal/config/... ./internal/settings/... -count=1

# -------------------------------------------------------------------
# Job 2 — Backend race test (QG-2 — the C-5/R-1 drain invariant)
Expand Down Expand Up @@ -247,7 +260,8 @@ jobs:

- name: Create test databases
# The full test suite exercises every package, each with its own
# isolated test DB. Create them all here.
# isolated test DB. Create them all here (including
# devteam_test_defaults for the settings/defaults package).
run: |
for db in devteam_test_db devteam_test_api devteam_test_spec devteam_test_intake devteam_test_pipeline devteam_test_chat devteam_test_config devteam_test_defaults; do
PGPASSWORD=devteam psql -h localhost -U devteam -d devteam -c "CREATE DATABASE $db;" || true
Expand Down
253 changes: 187 additions & 66 deletions .github/workflows/quality-gates.md

Large diffs are not rendered by default.

71 changes: 71 additions & 0 deletions internal/api/audit_handlers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package api

import (
"net/http"
"strconv"
"time"

"github.com/MichielDean/devteam/internal/db"
)

// ─── Audit read endpoint (Bolt 4 / v1 tab) ───
//
// GET /api/audit returns filtered, paginated config-mutation audit events
// (FR-AUDIT-01). Filters: type (single or comma-list), feature_id, actor,
// from/to (ISO 8601). Pagination: page (1-based), page_size (default 50,
// max 200). Read-only, unguarded (FR-ROUTE-02). Backed by
// idx_audit_events_type_time (FR-AUDIT-02).

func (s *Server) listAuditHandler(w http.ResponseWriter, r *http.Request) {
if s.db == nil {
writeJSON(w, http.StatusOK, map[string]interface{}{
"events": []db.AuditEvent{},
"total": 0,
"page": 1,
"page_size": 50,
})
return
}

q := r.URL.Query()
filter := db.AuditFilter{
EventType: q.Get("type"),
FeatureID: q.Get("feature_id"),
Actor: q.Get("actor"),
}
if fromStr := q.Get("from"); fromStr != "" {
if t, err := time.Parse(time.RFC3339, fromStr); err == nil {
filter.From = t
}
}
if toStr := q.Get("to"); toStr != "" {
if t, err := time.Parse(time.RFC3339, toStr); err == nil {
filter.To = t
}
}
if pageStr := q.Get("page"); pageStr != "" {
if p, err := strconv.Atoi(pageStr); err == nil {
filter.Page = p
}
}
if psStr := q.Get("page_size"); psStr != "" {
if ps, err := strconv.Atoi(psStr); err == nil {
filter.PageSize = ps
}
}

events, total, err := s.db.GetAuditEventsFiltered(filter)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to query audit events")
return
}
if events == nil {
events = []db.AuditEvent{}
}
writeJSON(w, http.StatusOK, map[string]interface{}{
"events": events,
"total": total,
"page": filter.Page,
"page_size": filter.PageSize,
})
}
59 changes: 59 additions & 0 deletions internal/api/auth_guard.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package api

import (
"net"
"net/http"
"os"
"strings"
)

// AdminGuard is the write-endpoint guard for the admin/settings route group
// (ADR-D6, FR-ROUTE-03). It allows:
//
// - localhost requests (RemoteAddr is 127.0.0.1, ::1, or localhost) — the
// single-operator dev workflow requires zero config.
// - requests carrying a matching X-Devteam-Admin-Token header — supports
// the trusted-LAN-access case.
//
// All other requests get 401 with the structured error shape
// {"error":"UNAUTHORIZED","details":"..."}. The guard is fail-closed: when
// DEVTEAM_ADMIN_TOKEN is unset and the request is non-localhost, it rejects
// (no accidental open writes — FR-ROUTE-03).
//
// Read routes (GET) skip this middleware (FR-ROUTE-02) — the route
// registration in server.go only wraps write methods.
//
// The guard is an http.Handler middleware, not inline checks, so a future
// RBAC feature can swap it without touching route registration (FR-ROUTE-04,
// NFR-MAINT-03).
func AdminGuard(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if isLocalhost(r) {
next.ServeHTTP(w, r)
return
}
token := os.Getenv("DEVTEAM_ADMIN_TOKEN")
if token != "" && r.Header.Get("X-Devteam-Admin-Token") == token {
next.ServeHTTP(w, r)
return
}
// Fail-closed: no token configured (or wrong token) + non-localhost.
writeJSON(w, http.StatusUnauthorized, ErrorResponse{
Error: "UNAUTHORIZED",
Details: "Admin write endpoints require a localhost request or a matching X-Devteam-Admin-Token header.",
})
})
}

// isLocalhost reports whether the request originated from the loopback
// address. RemoteAddr is host:port; we strip the port before comparing.
// Both IPv4 (127.0.0.1) and IPv6 (::1) loopback are accepted.
func isLocalhost(r *http.Request) bool {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
// No port — compare the whole RemoteAddr.
host = r.RemoteAddr
}
host = strings.TrimSpace(host)
return host == "127.0.0.1" || host == "::1" || host == "localhost"
}
152 changes: 152 additions & 0 deletions internal/api/auth_guard_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
package api

import (
"net/http"
"net/http/httptest"
"os"
"testing"
)

// TestGuard_LocalhostAllowed verifies a request from 127.0.0.1 is allowed
// through the guard with no token configured (S-ROUTE-03 AC2 — the
// single-operator dev workflow requires zero config).
func TestGuard_LocalhostAllowed(t *testing.T) {
os.Unsetenv("DEVTEAM_ADMIN_TOKEN")
called := false
guarded := AdminGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
}))

req := httptest.NewRequest(http.MethodPost, "/api/repos", nil)
req.RemoteAddr = "127.0.0.1:54321"
w := httptest.NewRecorder()
guarded.ServeHTTP(w, req)

if !called {
t.Error("handler not called for localhost request")
}
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
}

// TestGuard_IPv6LocalhostAllowed verifies ::1 is treated as localhost too.
func TestGuard_IPv6LocalhostAllowed(t *testing.T) {
os.Unsetenv("DEVTEAM_ADMIN_TOKEN")
called := false
guarded := AdminGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
}))

req := httptest.NewRequest(http.MethodPost, "/api/repos", nil)
req.RemoteAddr = "[::1]:54321"
w := httptest.NewRecorder()
guarded.ServeHTTP(w, req)

if !called {
t.Error("handler not called for ::1 request")
}
}

// TestGuard_ValidTokenAllowed verifies a non-localhost request with a
// matching X-Devteam-Admin-Token header is allowed (S-ROUTE-03 AC2 — the
// trusted-LAN-access case).
func TestGuard_ValidTokenAllowed(t *testing.T) {
os.Setenv("DEVTEAM_ADMIN_TOKEN", "secret-token")
t.Cleanup(func() { os.Unsetenv("DEVTEAM_ADMIN_TOKEN") })

called := false
guarded := AdminGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
}))

req := httptest.NewRequest(http.MethodPost, "/api/repos", nil)
req.RemoteAddr = "10.0.0.5:54321"
req.Header.Set("X-Devteam-Admin-Token", "secret-token")
w := httptest.NewRecorder()
guarded.ServeHTTP(w, req)

if !called {
t.Error("handler not called for valid-token request")
}
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
}

// TestGuard_MissingOrWrongToken_401 verifies a non-localhost request without
// a token (or with the wrong token) is rejected with 401 and produces no
// side effect (S-ROUTE-03 AC1, NFR-SEC-02).
func TestGuard_MissingOrWrongToken_401(t *testing.T) {
os.Setenv("DEVTEAM_ADMIN_TOKEN", "secret-token")
t.Cleanup(func() { os.Unsetenv("DEVTEAM_ADMIN_TOKEN") })

called := false
guarded := AdminGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
}))

// Missing token.
req := httptest.NewRequest(http.MethodPost, "/api/repos", nil)
req.RemoteAddr = "10.0.0.5:54321"
w := httptest.NewRecorder()
guarded.ServeHTTP(w, req)
if called {
t.Error("handler called for missing-token request (must not produce side effects)")
}
if w.Code != http.StatusUnauthorized {
t.Errorf("missing-token status = %d, want 401", w.Code)
}

// Wrong token.
called = false
req = httptest.NewRequest(http.MethodPost, "/api/repos", nil)
req.RemoteAddr = "10.0.0.5:54321"
req.Header.Set("X-Devteam-Admin-Token", "wrong-token")
w = httptest.NewRecorder()
guarded.ServeHTTP(w, req)
if called {
t.Error("handler called for wrong-token request")
}
if w.Code != http.StatusUnauthorized {
t.Errorf("wrong-token status = %d, want 401", w.Code)
}
}

// TestGuard_FailClosed_WhenEnvUnset verifies the fail-closed behavior: when
// DEVTEAM_ADMIN_TOKEN is unset and the request is non-localhost, the guard
// rejects with 401 (no accidental open writes — FR-ROUTE-03, R-AUTH-ABSENT).
func TestGuard_FailClosed_WhenEnvUnset(t *testing.T) {
os.Unsetenv("DEVTEAM_ADMIN_TOKEN")

called := false
guarded := AdminGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
}))

req := httptest.NewRequest(http.MethodPost, "/api/repos", nil)
req.RemoteAddr = "10.0.0.5:54321"
// No header set — env unset + non-localhost → fail-closed.
w := httptest.NewRecorder()
guarded.ServeHTTP(w, req)

if called {
t.Error("handler called for non-localhost request when token unset (fail-closed violated)")
}
if w.Code != http.StatusUnauthorized {
t.Errorf("status = %d, want 401 (fail-closed)", w.Code)
}
}

// TestGuard_PluggableMiddleware verifies AdminGuard is an http.Handler
// middleware (wraps an http.Handler, returns an http.Handler) — the
// FR-ROUTE-04 reviewer check that RBAC can swap it without route changes
// (NFR-MAINT-03).
func TestGuard_PluggableMiddleware(t *testing.T) {
var _ http.Handler = AdminGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
// If this compiles, AdminGuard is a middleware. The assertion is the
// type assignment above; no runtime check needed.
}
Loading
Loading