('getting-started')
+ // The tab lives in ?tab= so other pages can link straight to one,
+ // e.g. /setup?tab=settings for ingest keys.
+ const [searchParams, setSearchParams] = useSearchParams()
+ const tabParam = searchParams.get('tab')
+ const activeTab: TabId = isTabId(tabParam) ? tabParam : 'getting-started'
+ const setActiveTab = (id: TabId) => {
+ setSearchParams(id === 'getting-started' ? {} : { tab: id }, { replace: true })
+ }
return (
diff --git a/internal/api/auth/ingest_middleware_test.go b/internal/api/auth/ingest_middleware_test.go
new file mode 100644
index 0000000..a39944a
--- /dev/null
+++ b/internal/api/auth/ingest_middleware_test.go
@@ -0,0 +1,200 @@
+package auth_test
+
+import (
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/Flopsstuff/cotel/internal/api/auth"
+ "github.com/Flopsstuff/cotel/internal/ingest"
+ "github.com/Flopsstuff/cotel/internal/storage"
+)
+
+const (
+ liveIngestKey = "cotel_ik_" + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+ deadIngestKey = "cotel_ik_" + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
+ aliceToken = "cotel_" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ bobToken = "cotel_" + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+ unknownToken = "cotel_" + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
+)
+
+// fakeIngestAuthDB knows two actors and one live ingest key. keyErr makes every
+// IsIngestKey call fail, as a broken database would.
+type fakeIngestAuthDB struct {
+ allowAnonymous bool
+ keyErr error
+ keyLookups int
+}
+
+func (f *fakeIngestAuthDB) GetActorByToken(token string) (*storage.Actor, error) {
+ switch token {
+ case aliceToken:
+ return &storage.Actor{Name: "alice", Token: aliceToken}, nil
+ case bobToken:
+ return &storage.Actor{Name: "bob", Token: bobToken}, nil
+ }
+ return nil, errors.New("not found")
+}
+
+func (f *fakeIngestAuthDB) GetSettingBool(_ string, _ bool) bool { return f.allowAnonymous }
+
+func (f *fakeIngestAuthDB) IsIngestKey(token string) (bool, error) {
+ f.keyLookups++
+ if f.keyErr != nil {
+ return false, f.keyErr
+ }
+ return token == liveIngestKey, nil
+}
+
+// actorEcho answers 200 with the attributed actor name ("" when anonymous) in
+// a header, so a test can see what the middleware put in the context.
+var actorEcho = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Test-Actor", ingest.ActorNameFromContext(r.Context()))
+ w.WriteHeader(http.StatusOK)
+})
+
+func TestIngestMiddleware(t *testing.T) {
+ tests := []struct {
+ name string
+ allowAnonymous bool
+ keyErr error
+ bearer string // "" = no Authorization header
+ actorHeader string // "" = header not set
+ wantCode int
+ wantActor string
+ }{
+ // Ingest key in Authorization.
+ {"key + actor token", false, nil, liveIngestKey, aliceToken, 200, "alice"},
+ {"key + other actor token", false, nil, liveIngestKey, bobToken, 200, "bob"},
+ {"key, no actor header, anon off", false, nil, liveIngestKey, "", 200, ""},
+ {"key, no actor header, anon on", true, nil, liveIngestKey, "", 200, ""},
+ {"key + whitespace actor header", false, nil, liveIngestKey, " ", 200, ""},
+ {"key + unknown actor token", false, nil, liveIngestKey, unknownToken, 200, ""},
+ {"key + ingest key as actor token", false, nil, liveIngestKey, liveIngestKey, 200, ""},
+ {"unknown key", true, nil, deadIngestKey, "", 401, ""},
+ {"unknown key + valid actor header", true, nil, deadIngestKey, aliceToken, 401, ""},
+ {"key lookup error fails closed", true, errors.New("db down"), liveIngestKey, aliceToken, 401, ""},
+
+ // Actor token in Authorization: today's behaviour, header ignored.
+ {"actor bearer", false, nil, aliceToken, "", 200, "alice"},
+ {"actor bearer ignores actor header", false, nil, aliceToken, bobToken, 200, "alice"},
+ {"unknown actor bearer", true, nil, unknownToken, "", 401, ""},
+ {"unknown actor bearer + actor header", true, nil, unknownToken, aliceToken, 401, ""},
+
+ // No bearer: allow_anonymous decides, the actor header never identifies.
+ {"no bearer, anon on", true, nil, "", "", 200, ""},
+ {"no bearer, anon off", false, nil, "", "", 401, ""},
+ {"no bearer + actor header, anon on", true, nil, "", aliceToken, 200, ""},
+ {"no bearer + actor header, anon off", false, nil, "", aliceToken, 401, ""},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ db := &fakeIngestAuthDB{allowAnonymous: tt.allowAnonymous, keyErr: tt.keyErr}
+ h := auth.IngestMiddleware(db, actorEcho)
+ req := httptest.NewRequest(http.MethodPost, "/v1/traces", nil)
+ if tt.bearer != "" {
+ req.Header.Set("Authorization", "Bearer "+tt.bearer)
+ }
+ if tt.actorHeader != "" {
+ req.Header.Set(auth.ActorTokenHeader, tt.actorHeader)
+ }
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, req)
+
+ if w.Code != tt.wantCode {
+ t.Fatalf("status = %d, want %d (body %q)", w.Code, tt.wantCode, w.Body.String())
+ }
+ if tt.wantCode == http.StatusUnauthorized {
+ if got := w.Body.String(); got != `{"error":"unauthorized"}` {
+ t.Errorf("401 body = %q", got)
+ }
+ if ct := w.Header().Get("Content-Type"); ct != "application/json" {
+ t.Errorf("401 Content-Type = %q", ct)
+ }
+ return
+ }
+ if got := w.Header().Get("X-Test-Actor"); got != tt.wantActor {
+ t.Errorf("attributed actor = %q, want %q", got, tt.wantActor)
+ }
+ })
+ }
+}
+
+// Only cotel_ik_ bearers cost an ingest key lookup; actor tokens and anonymous
+// requests take exactly the old path.
+func TestIngestMiddleware_KeyLookupOnlyForKeys(t *testing.T) {
+ for _, bearer := range []string{"", aliceToken, unknownToken, "someOtherToken"} {
+ db := &fakeIngestAuthDB{allowAnonymous: true}
+ h := auth.IngestMiddleware(db, actorEcho)
+ req := httptest.NewRequest(http.MethodPost, "/v1/traces", nil)
+ if bearer != "" {
+ req.Header.Set("Authorization", "Bearer "+bearer)
+ }
+ h.ServeHTTP(httptest.NewRecorder(), req)
+ if db.keyLookups != 0 {
+ t.Errorf("bearer %q: %d ingest key lookups, want 0", bearer, db.keyLookups)
+ }
+ }
+}
+
+// Export and import stay on Middleware: an ingest key, which every agent can
+// read from its environment, must not authorize them.
+func TestMiddleware_RejectsIngestKey(t *testing.T) {
+ for _, allowAnonymous := range []bool{true, false} {
+ db := &fakeIngestAuthDB{allowAnonymous: allowAnonymous}
+ h := auth.Middleware(db, actorEcho)
+ req := httptest.NewRequest(http.MethodGet, "/api/v1/export", nil)
+ req.Header.Set("Authorization", "Bearer "+liveIngestKey)
+ req.Header.Set(auth.ActorTokenHeader, aliceToken)
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, req)
+ if w.Code != http.StatusUnauthorized {
+ t.Errorf("allow_anonymous=%v: ingest key on export got %d, want 401", allowAnonymous, w.Code)
+ }
+ }
+}
+
+// End to end against real storage: a key created in the database authorizes
+// ingest with the actor header attributing it, and stops working once deleted.
+func TestIngestMiddleware_RealStorage(t *testing.T) {
+ db, err := storage.Open(":memory:")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { db.Close() })
+ if err := db.SetSetting("allow_anonymous", "false"); err != nil {
+ t.Fatal(err)
+ }
+ actor, err := db.CreateActor("agent-7")
+ if err != nil {
+ t.Fatal(err)
+ }
+ key, err := db.CreateIngestKey("paperclip")
+ plaintext := key.Token
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ send := func(h http.Handler) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(http.MethodPost, "/v1/traces", nil)
+ req.Header.Set("Authorization", "Bearer "+plaintext)
+ req.Header.Set(auth.ActorTokenHeader, actor.Token)
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, req)
+ return w
+ }
+ h := auth.IngestMiddleware(db, actorEcho)
+ if w := send(h); w.Code != 200 || w.Header().Get("X-Test-Actor") != "agent-7" {
+ t.Fatalf("live key: code %d actor %q, want 200 agent-7", w.Code, w.Header().Get("X-Test-Actor"))
+ }
+ if w := send(auth.Middleware(db, actorEcho)); w.Code != http.StatusUnauthorized {
+ t.Fatalf("live key on Middleware: code %d, want 401", w.Code)
+ }
+ if err := db.DeleteIngestKey(key.ID); err != nil {
+ t.Fatal(err)
+ }
+ if w := send(h); w.Code != http.StatusUnauthorized {
+ t.Fatalf("deleted key: code %d, want 401", w.Code)
+ }
+}
diff --git a/internal/api/auth/middleware.go b/internal/api/auth/middleware.go
index ae0dece..203c771 100644
--- a/internal/api/auth/middleware.go
+++ b/internal/api/auth/middleware.go
@@ -2,6 +2,7 @@
package auth
import (
+ "log"
"net/http"
"strings"
@@ -33,17 +34,71 @@ func Middleware(db AuthDB, next http.Handler) http.Handler {
next.ServeHTTP(w, r.WithContext(ctx))
return
}
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusUnauthorized)
- _, _ = w.Write([]byte(`{"error":"unauthorized"}`))
+ unauthorized(w)
return
}
if db.GetSettingBool("allow_anonymous", true) {
next.ServeHTTP(w, r)
return
}
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusUnauthorized)
- _, _ = w.Write([]byte(`{"error":"unauthorized"}`))
+ unauthorized(w)
})
}
+
+// ActorTokenHeader carries an actor token next to an ingest key, so a fleet that
+// shares one Authorization header can still attribute each request.
+const ActorTokenHeader = "X-Cotel-Actor-Token"
+
+// IngestAuthDB is the database interface required by IngestMiddleware.
+// *storage.DB satisfies this interface.
+type IngestAuthDB interface {
+ AuthDB
+ IsIngestKey(token string) (bool, error)
+}
+
+// IngestMiddleware is Middleware plus shared ingest keys, for the OTLP ingest
+// endpoints only. An ingest key authorizes a request but does not identify it;
+// identity comes from an actor token in the X-Cotel-Actor-Token header.
+//
+// Rules:
+// - valid cotel_ik_* bearer → allow; attribute to the actor whose token is in
+// X-Cotel-Actor-Token, or anonymously when that header is absent or unknown
+// (even with allow_anonymous=false, since the key authorized the request)
+// - unknown cotel_ik_* bearer, or a database error checking it → 401
+// - any other bearer, or none → exactly Middleware; X-Cotel-Actor-Token is
+// ignored, so it never identifies a request on its own
+//
+// It never writes to the database: ingest is high frequency and DuckDB has a
+// single writer.
+func IngestMiddleware(db IngestAuthDB, next http.Handler) http.Handler {
+ fallback := Middleware(db, next)
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ bearer := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
+ if !strings.HasPrefix(bearer, storage.IngestKeyPrefix) {
+ fallback.ServeHTTP(w, r)
+ return
+ }
+ ok, err := db.IsIngestKey(bearer)
+ if err != nil {
+ log.Printf("auth: ingest key lookup failed: %v", err)
+ unauthorized(w)
+ return
+ }
+ if !ok {
+ unauthorized(w)
+ return
+ }
+ if token := strings.TrimSpace(r.Header.Get(ActorTokenHeader)); token != "" {
+ if actor, err := db.GetActorByToken(token); err == nil && actor != nil {
+ r = r.WithContext(ingest.WithActorName(r.Context(), actor.Name))
+ }
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
+func unauthorized(w http.ResponseWriter) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusUnauthorized)
+ _, _ = w.Write([]byte(`{"error":"unauthorized"}`))
+}
diff --git a/internal/api/handler.go b/internal/api/handler.go
index 41fe8e0..02f4b16 100644
--- a/internal/api/handler.go
+++ b/internal/api/handler.go
@@ -26,6 +26,7 @@ type Handler struct {
db DB
tokenDB TokenStore
actorStore ActorStore
+ ingestKeyStore IngestKeyStore
publicIngestURL string
}
@@ -95,6 +96,10 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} else {
h.handleActorByID(w, r, rest)
}
+ case path == "/ingest-keys" || path == "/ingest-keys/":
+ h.handleIngestKeys(w, r)
+ case strings.HasPrefix(path, "/ingest-keys/"):
+ h.handleIngestKeyByID(w, r, strings.TrimPrefix(path, "/ingest-keys/"))
case path == "/settings" || path == "/settings/":
h.handleSettings(w, r)
case path == "/health" || path == "/health/":
diff --git a/internal/api/ingest_keys.go b/internal/api/ingest_keys.go
new file mode 100644
index 0000000..162b329
--- /dev/null
+++ b/internal/api/ingest_keys.go
@@ -0,0 +1,126 @@
+package api
+
+import (
+ "encoding/json"
+ "errors"
+ "net/http"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/Flopsstuff/cotel/internal/storage"
+)
+
+// maxIngestKeyName bounds an ingest key's display name, in characters.
+const maxIngestKeyName = 100
+
+// IngestKeyStore is the write-capable interface used by the ingest key endpoints.
+type IngestKeyStore interface {
+ CreateIngestKey(name string) (storage.IngestKey, error)
+ ListIngestKeys() ([]storage.IngestKey, error)
+ DeleteIngestKey(id string) error
+}
+
+// SetIngestKeyStore attaches a writable store for the /ingest-keys endpoints.
+func (h *Handler) SetIngestKeyStore(s IngestKeyStore) *Handler {
+ h.ingestKeyStore = s
+ return h
+}
+
+// ingestKeyItem is one key as the list and create endpoints return it. The
+// token is included, like an actor's: keys are retrievable by design (ADR-0028).
+type ingestKeyItem struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Token string `json:"token"`
+ CreatedAt string `json:"created_at"`
+}
+
+func toIngestKeyItem(k storage.IngestKey) ingestKeyItem {
+ return ingestKeyItem{
+ ID: k.ID,
+ Name: k.Name,
+ Token: k.Token,
+ CreatedAt: k.CreatedAt.UTC().Format(time.RFC3339),
+ }
+}
+
+// handleIngestKeys dispatches GET (list) and POST (create) on /api/v1/ingest-keys.
+func (h *Handler) handleIngestKeys(w http.ResponseWriter, r *http.Request) {
+ if h.ingestKeyStore == nil {
+ jsonError(w, "not found", http.StatusNotFound)
+ return
+ }
+ switch r.Method {
+ case http.MethodGet:
+ h.listIngestKeys(w)
+ case http.MethodPost:
+ h.createIngestKey(w, r)
+ default:
+ jsonError(w, "method not allowed", http.StatusMethodNotAllowed)
+ }
+}
+
+// handleIngestKeyByID handles DELETE /api/v1/ingest-keys/{id} (revoke).
+func (h *Handler) handleIngestKeyByID(w http.ResponseWriter, r *http.Request, id string) {
+ if h.ingestKeyStore == nil || id == "" || strings.Contains(id, "/") {
+ jsonError(w, "not found", http.StatusNotFound)
+ return
+ }
+ if r.Method != http.MethodDelete {
+ jsonError(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ err := h.ingestKeyStore.DeleteIngestKey(id)
+ if errors.Is(err, storage.ErrNotFound) {
+ jsonError(w, "not found", http.StatusNotFound)
+ return
+ }
+ if err != nil {
+ jsonError(w, "delete failed", http.StatusInternalServerError)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
+func (h *Handler) listIngestKeys(w http.ResponseWriter) {
+ keys, err := h.ingestKeyStore.ListIngestKeys()
+ if err != nil {
+ queryFailed(w)
+ return
+ }
+ items := make([]ingestKeyItem, 0, len(keys))
+ for _, k := range keys {
+ items = append(items, toIngestKeyItem(k))
+ }
+ jsonOK(w, struct {
+ IngestKeys []ingestKeyItem `json:"ingest_keys"`
+ }{items})
+}
+
+func (h *Handler) createIngestKey(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ Name string `json:"name"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ jsonError(w, "invalid JSON body", http.StatusBadRequest)
+ return
+ }
+ name := strings.TrimSpace(req.Name)
+ if name == "" {
+ jsonError(w, "name required", http.StatusBadRequest)
+ return
+ }
+ if utf8.RuneCountInString(name) > maxIngestKeyName {
+ jsonError(w, "name must be at most 100 characters", http.StatusBadRequest)
+ return
+ }
+ k, err := h.ingestKeyStore.CreateIngestKey(name)
+ if err != nil {
+ jsonError(w, "create failed", http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusCreated)
+ _ = json.NewEncoder(w).Encode(toIngestKeyItem(k))
+}
diff --git a/internal/api/ingest_keys_test.go b/internal/api/ingest_keys_test.go
new file mode 100644
index 0000000..361fa2d
--- /dev/null
+++ b/internal/api/ingest_keys_test.go
@@ -0,0 +1,162 @@
+package api_test
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Flopsstuff/cotel/internal/api"
+ "github.com/Flopsstuff/cotel/internal/storage"
+)
+
+func newIngestKeyHandler(t *testing.T, db *storage.DB, ro *storage.ReadDB) http.Handler {
+ t.Helper()
+ return api.New(ro).SetActorStore(db).SetIngestKeyStore(db)
+}
+
+func doIngestKeys(t *testing.T, h http.Handler, method, path, body string) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest(method, path, strings.NewReader(body))
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, req)
+ return w
+}
+
+func TestIngestKeys_ListEmpty(t *testing.T) {
+ db, ro := openTestDB(t)
+ h := newIngestKeyHandler(t, db, ro)
+
+ w := doIngestKeys(t, h, http.MethodGet, "/api/v1/ingest-keys", "")
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", w.Code)
+ }
+ if got := strings.TrimSpace(w.Body.String()); got != `{"ingest_keys":[]}` {
+ t.Fatalf("body = %s, want an empty array, not null", got)
+ }
+}
+
+func TestIngestKeys_CreateListDelete(t *testing.T) {
+ db, ro := openTestDB(t)
+ h := newIngestKeyHandler(t, db, ro)
+
+ w := doIngestKeys(t, h, http.MethodPost, "/api/v1/ingest-keys", `{"name":" Paperclip "}`)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("create: status = %d, want 201 (%s)", w.Code, w.Body.String())
+ }
+ var created struct {
+ ID, Name, Token string
+ CreatedAt string `json:"created_at"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil {
+ t.Fatalf("create body: %v", err)
+ }
+ if created.Name != "Paperclip" {
+ t.Errorf("name = %q, want trimmed %q", created.Name, "Paperclip")
+ }
+ if !regexp.MustCompile(`^cotel_ik_[0-9a-f]{64}$`).MatchString(created.Token) {
+ t.Errorf("token = %q", created.Token)
+ }
+ if ts, err := time.Parse(time.RFC3339, created.CreatedAt); err != nil || ts.Location() != time.UTC {
+ t.Errorf("created_at = %q, want RFC3339 UTC (err %v)", created.CreatedAt, err)
+ }
+ if ok, err := db.IsIngestKey(created.Token); err != nil || !ok {
+ t.Fatalf("created token not accepted: ok=%v err=%v", ok, err)
+ }
+
+ code, body := getJSON(t, h, "/api/v1/ingest-keys")
+ if code != http.StatusOK {
+ t.Fatalf("list: status = %d", code)
+ }
+ keys, _ := body["ingest_keys"].([]any)
+ if len(keys) != 1 {
+ t.Fatalf("list: %d keys, want 1", len(keys))
+ }
+ item := keys[0].(map[string]any)
+ // The list returns the token so it can be copied again, like an actor token.
+ if item["id"] != created.ID || item["name"] != "Paperclip" || item["token"] != created.Token ||
+ item["created_at"] != created.CreatedAt {
+ t.Errorf("list item = %v", item)
+ }
+
+ if w := doIngestKeys(t, h, http.MethodDelete, "/api/v1/ingest-keys/"+created.ID, ""); w.Code != http.StatusNoContent {
+ t.Fatalf("delete: status = %d, want 204", w.Code)
+ }
+ if ok, _ := db.IsIngestKey(created.Token); ok {
+ t.Fatal("deleted key still accepted")
+ }
+ w = doIngestKeys(t, h, http.MethodDelete, "/api/v1/ingest-keys/"+created.ID, "")
+ if w.Code != http.StatusNotFound || strings.TrimSpace(w.Body.String()) != `{"error":"not found"}` {
+ t.Fatalf("delete again: %d %s, want 404 not found", w.Code, w.Body.String())
+ }
+}
+
+func TestIngestKeys_CreateValidation(t *testing.T) {
+ db, ro := openTestDB(t)
+ h := newIngestKeyHandler(t, db, ro)
+
+ tests := []struct {
+ name string
+ body string
+ wantCode int
+ }{
+ {"missing name", `{}`, 400},
+ {"empty name", `{"name":""}`, 400},
+ {"blank name", `{"name":" "}`, 400},
+ {"not json", `name=x`, 400},
+ {"wrong type", `{"name":7}`, 400},
+ {"101 chars", `{"name":"` + strings.Repeat("a", 101) + `"}`, 400},
+ {"100 chars", `{"name":"` + strings.Repeat("a", 100) + `"}`, 201},
+ {"100 multibyte chars", `{"name":"` + strings.Repeat("é", 100) + `"}`, 201},
+ {"100 chars after trim", `{"name":" ` + strings.Repeat("a", 100) + ` "}`, 201},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ w := doIngestKeys(t, h, http.MethodPost, "/api/v1/ingest-keys", tt.body)
+ if w.Code != tt.wantCode {
+ t.Fatalf("status = %d, want %d (%s)", w.Code, tt.wantCode, w.Body.String())
+ }
+ if tt.wantCode == http.StatusBadRequest {
+ var e map[string]string
+ if err := json.Unmarshal(w.Body.Bytes(), &e); err != nil || e["error"] == "" {
+ t.Errorf("400 body = %s, want {\"error\":...}", w.Body.String())
+ }
+ }
+ })
+ }
+}
+
+func TestIngestKeys_Methods(t *testing.T) {
+ db, ro := openTestDB(t)
+ h := newIngestKeyHandler(t, db, ro)
+
+ tests := []struct {
+ method, path string
+ wantCode int
+ }{
+ {http.MethodPut, "/api/v1/ingest-keys", 405},
+ {http.MethodDelete, "/api/v1/ingest-keys", 405},
+ {http.MethodPatch, "/api/v1/ingest-keys", 405},
+ {http.MethodGet, "/api/v1/ingest-keys/some-id", 405},
+ {http.MethodPost, "/api/v1/ingest-keys/some-id", 405},
+ {http.MethodDelete, "/api/v1/ingest-keys/unknown-id", 404},
+ }
+ for _, tt := range tests {
+ w := doIngestKeys(t, h, tt.method, tt.path, "")
+ if w.Code != tt.wantCode {
+ t.Errorf("%s %s: status = %d, want %d", tt.method, tt.path, w.Code, tt.wantCode)
+ }
+ }
+}
+
+// Without a store attached the endpoints do not exist, like /actors.
+func TestIngestKeys_NoStore(t *testing.T) {
+ _, ro := openTestDB(t)
+ h := api.New(ro)
+ if w := doIngestKeys(t, h, http.MethodGet, "/api/v1/ingest-keys", ""); w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404", w.Code)
+ }
+}
diff --git a/internal/ingest/handler.go b/internal/ingest/handler.go
index 59f60e6..5df9cb1 100644
--- a/internal/ingest/handler.go
+++ b/internal/ingest/handler.go
@@ -98,9 +98,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusOK)
- _, _ = w.Write([]byte(`{}`))
+ writeOTLPSuccess(w, r)
}
// sessionIDKeys are the attribute key names Claude Code may use for the session
diff --git a/internal/ingest/handler_test.go b/internal/ingest/handler_test.go
index c0bbeb4..5061637 100644
--- a/internal/ingest/handler_test.go
+++ b/internal/ingest/handler_test.go
@@ -310,3 +310,33 @@ func TestUnknownModelCostIsNil(t *testing.T) {
t.Errorf("unknown model: cost_usd should be nil, got %v", *s.CostUSD)
}
}
+
+// A protobuf export must be answered with a protobuf ExportTraceServiceResponse
+// (an empty one is zero bytes), not with JSON: protobuf exporters decode the body.
+func TestTracesResponseMatchesRequestEncoding(t *testing.T) {
+ cases := []struct {
+ name, contentType, wantCT, wantBody string
+ body []byte
+ }{
+ {"protobuf", "application/x-protobuf", "application/x-protobuf", "", nil},
+ {"json", "application/json", "application/json", `{}`, []byte(`{"resourceSpans":[]}`)},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ h := ingest.New(&memStore{})
+ req := httptest.NewRequest(http.MethodPost, "/v1/traces", bytes.NewReader(c.body))
+ req.Header.Set("Content-Type", c.contentType)
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d (%s)", w.Code, w.Body.String())
+ }
+ if ct := w.Header().Get("Content-Type"); ct != c.wantCT {
+ t.Errorf("Content-Type = %q, want %q", ct, c.wantCT)
+ }
+ if got := w.Body.String(); got != c.wantBody {
+ t.Errorf("body = %q, want %q", got, c.wantBody)
+ }
+ })
+ }
+}
diff --git a/internal/ingest/logs.go b/internal/ingest/logs.go
new file mode 100644
index 0000000..f3d7bf3
--- /dev/null
+++ b/internal/ingest/logs.go
@@ -0,0 +1,28 @@
+package ingest
+
+import (
+ "io"
+ "net/http"
+)
+
+// maxLogsBody caps how much of a /v1/logs body is read before it is discarded.
+const maxLogsBody = 10 << 20 // 10 MiB
+
+// LogsSink accepts OTLP/HTTP log exports (POST /v1/logs) and discards them.
+// cotel stores traces only, but exporters that also send logs (Claude Code run
+// by Paperclip, for one) retry or complain on a 404, so the endpoint answers
+// success with an empty ExportLogsServiceResponse.
+type LogsSink struct{}
+
+// NewLogsSink returns the /v1/logs handler.
+func NewLogsSink() LogsSink { return LogsSink{} }
+
+func (LogsSink) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ w.Header().Set("Allow", http.MethodPost)
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ _, _ = io.Copy(io.Discard, http.MaxBytesReader(w, r.Body, maxLogsBody))
+ writeOTLPSuccess(w, r)
+}
diff --git a/internal/ingest/logs_test.go b/internal/ingest/logs_test.go
new file mode 100644
index 0000000..7269574
--- /dev/null
+++ b/internal/ingest/logs_test.go
@@ -0,0 +1,52 @@
+package ingest
+
+import (
+ "bytes"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestLogsSink(t *testing.T) {
+ tests := []struct {
+ name string
+ method string
+ contentType string
+ body []byte
+ wantCode int
+ wantCT string
+ wantBody string
+ }{
+ // An empty ExportLogsServiceResponse encodes to zero protobuf bytes.
+ {"post protobuf", http.MethodPost, "application/x-protobuf", []byte{0x0a, 0x02, 0x08, 0x01}, 200, "application/x-protobuf", ""},
+ {"post json", http.MethodPost, "application/json", []byte(`{"resourceLogs":[]}`), 200, "application/json", `{}`},
+ {"post json with charset", http.MethodPost, "application/json; charset=utf-8", []byte(`{}`), 200, "application/json", `{}`},
+ {"post empty, no content type", http.MethodPost, "", nil, 200, "application/json", `{}`},
+ {"post over the cap", http.MethodPost, "application/x-protobuf", bytes.Repeat([]byte("x"), maxLogsBody+1), 200, "application/x-protobuf", ""},
+ {"get", http.MethodGet, "application/x-protobuf", nil, 405, "", ""},
+ {"put", http.MethodPut, "application/x-protobuf", nil, 405, "", ""},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ req := httptest.NewRequest(tt.method, "/v1/logs", bytes.NewReader(tt.body))
+ if tt.contentType != "" {
+ req.Header.Set("Content-Type", tt.contentType)
+ }
+ w := httptest.NewRecorder()
+ NewLogsSink().ServeHTTP(w, req)
+
+ if w.Code != tt.wantCode {
+ t.Fatalf("status = %d, want %d", w.Code, tt.wantCode)
+ }
+ if tt.wantCode != http.StatusOK {
+ return
+ }
+ if got := w.Body.String(); got != tt.wantBody {
+ t.Errorf("body = %q, want %q", got, tt.wantBody)
+ }
+ if ct := w.Header().Get("Content-Type"); ct != tt.wantCT {
+ t.Errorf("Content-Type = %q, want %q", ct, tt.wantCT)
+ }
+ })
+ }
+}
diff --git a/internal/ingest/response.go b/internal/ingest/response.go
new file mode 100644
index 0000000..f0ed32f
--- /dev/null
+++ b/internal/ingest/response.go
@@ -0,0 +1,29 @@
+package ingest
+
+import (
+ "net/http"
+ "strings"
+)
+
+// writeOTLPSuccess answers a successful OTLP/HTTP export in the encoding the
+// request used, as the OTLP spec requires: an empty JSON object for a JSON
+// request, and an empty Export*ServiceResponse - which encodes to zero bytes -
+// for a protobuf one. Exporters that use protobuf (Claude Code when Paperclip
+// configures it) try to decode the body as protobuf, and a JSON "{}" is not one.
+func writeOTLPSuccess(w http.ResponseWriter, r *http.Request) {
+ if isJSONRequest(r) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{}`))
+ return
+ }
+ w.Header().Set("Content-Type", "application/x-protobuf")
+ w.WriteHeader(http.StatusOK)
+}
+
+// isJSONRequest reports whether an OTLP request body is JSON. A missing
+// Content-Type is treated as JSON, matching how the traces handler decodes it.
+func isJSONRequest(r *http.Request) bool {
+ ct := r.Header.Get("Content-Type")
+ return ct == "" || strings.HasPrefix(ct, "application/json")
+}
diff --git a/internal/storage/actors_migration_test.go b/internal/storage/actors_migration_test.go
index 25ca031..f146f07 100644
--- a/internal/storage/actors_migration_test.go
+++ b/internal/storage/actors_migration_test.go
@@ -58,8 +58,8 @@ func TestMigrateUsersToActors_FromV10(t *testing.T) {
}
defer db.Close()
- if v, _ := appliedSchemaVersion(db.rw); v != 11 {
- t.Fatalf("schema version = %d, want 11", v)
+ if v, want := appliedVersion(t, db), embeddedVersion(t); v != want {
+ t.Fatalf("schema version = %d, want %d", v, want)
}
// The old names are gone, so no query can silently read an empty twin.
diff --git a/internal/storage/ingest_keys.go b/internal/storage/ingest_keys.go
new file mode 100644
index 0000000..9d9ff16
--- /dev/null
+++ b/internal/storage/ingest_keys.go
@@ -0,0 +1,105 @@
+package storage
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "strings"
+ "time"
+)
+
+// IngestKeyPrefix starts every ingest key plaintext. It is a sub-prefix of the
+// actor token prefix "cotel_", so callers that tell the two apart must check
+// this one first.
+const IngestKeyPrefix = "cotel_ik_"
+
+// IngestKey is a shared key that authorizes OTLP ingest without identifying an
+// actor. Like actor tokens it is stored in plaintext and always retrievable, so
+// an operator can copy it again into another sender's configuration.
+type IngestKey struct {
+ ID string
+ Name string
+ Token string
+ CreatedAt time.Time
+}
+
+func generateIngestKey() (string, error) {
+ var b [32]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ return "", err
+ }
+ return IngestKeyPrefix + hex.EncodeToString(b[:]), nil
+}
+
+// CreateIngestKey stores a new ingest key under name and returns it.
+func (db *DB) CreateIngestKey(name string) (IngestKey, error) {
+ token, err := generateIngestKey()
+ if err != nil {
+ return IngestKey{}, err
+ }
+ id := generateID()
+ if _, err := db.rw.Exec(
+ `INSERT INTO ingest_keys (id, name, token) VALUES (?, ?, ?)`, id, name, token,
+ ); err != nil {
+ return IngestKey{}, err
+ }
+ var k IngestKey
+ if err := db.rw.QueryRow(
+ `SELECT id, name, token, created_at FROM ingest_keys WHERE id = ?`, id,
+ ).Scan(&k.ID, &k.Name, &k.Token, &k.CreatedAt); err != nil {
+ return IngestKey{}, err
+ }
+ return k, nil
+}
+
+// ListIngestKeys returns every ingest key, oldest first.
+func (db *DB) ListIngestKeys() ([]IngestKey, error) {
+ rows, err := db.rw.Query(
+ `SELECT id, name, token, created_at FROM ingest_keys ORDER BY created_at ASC, id ASC`,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []IngestKey{}
+ for rows.Next() {
+ var k IngestKey
+ if err := rows.Scan(&k.ID, &k.Name, &k.Token, &k.CreatedAt); err != nil {
+ return nil, err
+ }
+ out = append(out, k)
+ }
+ return out, rows.Err()
+}
+
+// DeleteIngestKey revokes an ingest key by deleting its row. Returns
+// ErrNotFound when no key has that id.
+func (db *DB) DeleteIngestKey(id string) error {
+ result, err := db.rw.Exec(`DELETE FROM ingest_keys WHERE id = ?`, id)
+ if err != nil {
+ return err
+ }
+ n, err := result.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if n == 0 {
+ return ErrNotFound
+ }
+ return nil
+}
+
+// IsIngestKey reports whether plaintext is a live ingest key. Anything not
+// shaped like one is rejected without touching the database. It only reads, so
+// it is safe on the hot ingest path.
+func (db *DB) IsIngestKey(plaintext string) (bool, error) {
+ if !strings.HasPrefix(plaintext, IngestKeyPrefix) {
+ return false, nil
+ }
+ var n int
+ if err := db.rw.QueryRow(
+ `SELECT count(*) FROM ingest_keys WHERE token = ?`, plaintext,
+ ).Scan(&n); err != nil {
+ return false, err
+ }
+ return n > 0, nil
+}
diff --git a/internal/storage/ingest_keys_test.go b/internal/storage/ingest_keys_test.go
new file mode 100644
index 0000000..0f4630c
--- /dev/null
+++ b/internal/storage/ingest_keys_test.go
@@ -0,0 +1,242 @@
+package storage
+
+import (
+ "database/sql"
+ "errors"
+ "os"
+ "path/filepath"
+ "regexp"
+ "testing"
+)
+
+var ingestKeyRe = regexp.MustCompile(`^cotel_ik_[0-9a-f]{64}$`)
+
+func TestCreateIngestKey_RetrievableToken(t *testing.T) {
+ db := openTestActorDB(t)
+
+ k, err := db.CreateIngestKey("paperclip")
+ if err != nil {
+ t.Fatalf("CreateIngestKey: %v", err)
+ }
+ if !ingestKeyRe.MatchString(k.Token) {
+ t.Fatalf("token %q does not match %s", k.Token, ingestKeyRe)
+ }
+ if k.ID == "" || k.Name != "paperclip" || k.CreatedAt.IsZero() {
+ t.Fatalf("record = %+v", k)
+ }
+ // The token is kept so it can be copied again later, like an actor token.
+ keys, err := db.ListIngestKeys()
+ if err != nil || len(keys) != 1 || keys[0].Token != k.Token {
+ t.Fatalf("list = %+v (err %v), want the created token back", keys, err)
+ }
+}
+
+func TestCreateIngestKey_Unique(t *testing.T) {
+ db := openTestActorDB(t)
+ a, err := db.CreateIngestKey("same")
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := db.CreateIngestKey("same")
+ if err != nil {
+ t.Fatalf("second key with the same name: %v", err)
+ }
+ if a.Token == b.Token {
+ t.Fatal("two keys share a token")
+ }
+}
+
+func TestListIngestKeys(t *testing.T) {
+ db := openTestActorDB(t)
+
+ keys, err := db.ListIngestKeys()
+ if err != nil {
+ t.Fatalf("ListIngestKeys (empty): %v", err)
+ }
+ if keys == nil || len(keys) != 0 {
+ t.Fatalf("empty list = %#v, want non-nil empty slice", keys)
+ }
+
+ var want []string
+ for _, name := range []string{"first", "second", "third"} {
+ k, err := db.CreateIngestKey(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Pin distinct creation times so "oldest first" is observable.
+ if _, err := db.rw.Exec(
+ `UPDATE ingest_keys SET created_at = TIMESTAMPTZ '2026-01-01 00:00:00+00' + to_days(?) WHERE id = ?`,
+ len(want), k.ID,
+ ); err != nil {
+ t.Fatalf("pin created_at: %v", err)
+ }
+ want = append(want, name)
+ }
+
+ keys, err = db.ListIngestKeys()
+ if err != nil {
+ t.Fatalf("ListIngestKeys: %v", err)
+ }
+ if len(keys) != len(want) {
+ t.Fatalf("got %d keys, want %d", len(keys), len(want))
+ }
+ for i, k := range keys {
+ if k.Name != want[i] {
+ t.Errorf("keys[%d] = %q, want %q (oldest first)", i, k.Name, want[i])
+ }
+ }
+}
+
+func TestDeleteIngestKey(t *testing.T) {
+ db := openTestActorDB(t)
+ k, err := db.CreateIngestKey("doomed")
+ plaintext := k.Token
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if err := db.DeleteIngestKey(k.ID); err != nil {
+ t.Fatalf("DeleteIngestKey: %v", err)
+ }
+ if n := queryInt64(t, db, `SELECT count(*) FROM ingest_keys WHERE id = ?`, k.ID); n != 0 {
+ t.Fatalf("row survived delete")
+ }
+ if ok, err := db.IsIngestKey(plaintext); err != nil || ok {
+ t.Fatalf("deleted key still valid: ok=%v err=%v", ok, err)
+ }
+ if err := db.DeleteIngestKey(k.ID); !errors.Is(err, ErrNotFound) {
+ t.Fatalf("second delete: err = %v, want ErrNotFound", err)
+ }
+ if err := db.DeleteIngestKey("no-such-id"); !errors.Is(err, ErrNotFound) {
+ t.Fatalf("unknown id: err = %v, want ErrNotFound", err)
+ }
+}
+
+func TestIsIngestKey(t *testing.T) {
+ db := openTestActorDB(t)
+ live, err := db.CreateIngestKey("live")
+ plaintext := live.Token
+ if err != nil {
+ t.Fatal(err)
+ }
+ actor := mustCreateTestActor(t, db, "alice")
+
+ tests := []struct {
+ name string
+ token string
+ want bool
+ }{
+ {"live key", plaintext, true},
+ {"empty", "", false},
+ {"actor token", actor.Token, false},
+ {"unknown key", "cotel_ik_" + repeatHex("0"), false},
+ {"prefix only", "cotel_ik_", false},
+ {"display prefix", plaintext[:12], false},
+ {"key with trailing space", plaintext + " ", false},
+ {"no prefix", plaintext[len("cotel_ik_"):], false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := db.IsIngestKey(tt.token)
+ if err != nil {
+ t.Fatalf("IsIngestKey: %v", err)
+ }
+ if got != tt.want {
+ t.Fatalf("IsIngestKey(%q) = %v, want %v", tt.token, got, tt.want)
+ }
+ })
+ }
+}
+
+// seedV11 builds a database exactly as schema version 11 left it: testdata holds
+// a frozen copy of that release's schema.sql, applied and hash-recorded the way
+// a v11 binary would have done it.
+func seedV11(t *testing.T, path string) {
+ t.Helper()
+ ddl, err := os.ReadFile(filepath.Join("testdata", "schema_v11.sql"))
+ if err != nil {
+ t.Fatalf("read v11 schema: %v", err)
+ }
+ raw, err := sql.Open("duckdb", path)
+ if err != nil {
+ t.Fatalf("raw open: %v", err)
+ }
+ defer raw.Close()
+ if _, err := raw.Exec(string(ddl)); err != nil {
+ t.Fatalf("apply v11 schema: %v", err)
+ }
+ if err := recordSchemaSHA(raw, "v11-sha"); err != nil {
+ t.Fatalf("record v11 sha: %v", err)
+ }
+ if _, err := raw.Exec(`INSERT INTO actors (id, name, token) VALUES ('a1', 'Daedalus', 'cotel_` + repeatHex("a") + `')`); err != nil {
+ t.Fatalf("seed actor: %v", err)
+ }
+}
+
+// A v11 database gains ingest_keys and schema_version 12 on open, keeps its
+// data, and a second open is a no-op.
+func TestSchemaV12_FromV11(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "v11.duckdb")
+ seedV11(t, path)
+
+ for i := 0; i < 2; i++ {
+ db, err := Open(path)
+ if err != nil {
+ t.Fatalf("open #%d: %v", i+1, err)
+ }
+ if v := appliedVersion(t, db); v != 12 {
+ t.Fatalf("open #%d: schema version = %d, want 12", i+1, v)
+ }
+ if n := queryInt64(t, db, `SELECT count(*) FROM actors WHERE name = 'Daedalus'`); n != 1 {
+ t.Fatalf("open #%d: v11 actor lost (%d rows)", i+1, n)
+ }
+ if i == 0 {
+ if _, err := db.CreateIngestKey("fleet"); err != nil {
+ t.Fatalf("CreateIngestKey on migrated db: %v", err)
+ }
+ }
+ keys, err := db.ListIngestKeys()
+ if err != nil {
+ t.Fatalf("open #%d: ListIngestKeys: %v", i+1, err)
+ }
+ if len(keys) != 1 || keys[0].Name != "fleet" {
+ t.Fatalf("open #%d: ingest keys = %+v, want the one created", i+1, keys)
+ }
+ if err := db.Close(); err != nil {
+ t.Fatalf("close #%d: %v", i+1, err)
+ }
+ }
+}
+
+// Re-applying schema.sql over a database that already has ingest keys (any
+// hash change does this) must leave them intact.
+func TestSchemaV12_ReapplyKeepsKeys(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "reapply.duckdb")
+ db, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ kept, err := db.CreateIngestKey("keep")
+ plaintext := kept.Token
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := db.SetSetting(schemaSHAKey, "stale"); err != nil {
+ t.Fatal(err)
+ }
+ if err := db.Close(); err != nil {
+ t.Fatal(err)
+ }
+
+ db2, err := Open(path)
+ if err != nil {
+ t.Fatalf("reopen: %v", err)
+ }
+ defer db2.Close()
+ if appliedSchemaSHA(db2.rw) != embeddedSHA(t) {
+ t.Fatal("schema was not re-applied")
+ }
+ if ok, err := db2.IsIngestKey(plaintext); err != nil || !ok {
+ t.Fatalf("key lost on re-apply: ok=%v err=%v", ok, err)
+ }
+}
diff --git a/internal/storage/schema.sql b/internal/storage/schema.sql
index f3715be..a1ccf38 100644
--- a/internal/storage/schema.sql
+++ b/internal/storage/schema.sql
@@ -1,4 +1,4 @@
--- Schema version: 11
+-- Schema version: 12
-- Versioned; never silently rename columns.
CREATE TABLE IF NOT EXISTS schema_version (
@@ -149,6 +149,17 @@ WHERE NOT EXISTS (SELECT 1 FROM actors u WHERE u.name = t.actor_id)
-- Migration v6 → v7: add deleted_at for soft-delete support.
ALTER TABLE actors ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ DEFAULT NULL;
+-- v12: shared ingest keys (ADR-0028). One key authorizes OTLP ingest for a
+-- whole fleet (e.g. Paperclip, which sends one header set for every agent);
+-- identity still comes from an actor token in X-Cotel-Actor-Token. Stored in
+-- plaintext and always retrievable, like actor tokens. Revoking deletes the row.
+CREATE TABLE IF NOT EXISTS ingest_keys (
+ id VARCHAR PRIMARY KEY,
+ name VARCHAR NOT NULL,
+ token VARCHAR NOT NULL UNIQUE,
+ created_at TIMESTAMPTZ DEFAULT now()
+);
+
INSERT INTO schema_version (version) VALUES (1) ON CONFLICT DO NOTHING;
INSERT INTO schema_version (version) VALUES (2) ON CONFLICT DO NOTHING;
INSERT INTO schema_version (version) VALUES (3) ON CONFLICT DO NOTHING;
@@ -163,3 +174,4 @@ INSERT INTO schema_version (version) VALUES (10) ON CONFLICT DO NOTHING;
-- idempotently in SQL, so it is not in this file: migrateUsersToActors in
-- duckdb.go runs it before this file is applied (ADR-0027).
INSERT INTO schema_version (version) VALUES (11) ON CONFLICT DO NOTHING;
+INSERT INTO schema_version (version) VALUES (12) ON CONFLICT DO NOTHING;
diff --git a/internal/storage/testdata/schema_v11.sql b/internal/storage/testdata/schema_v11.sql
new file mode 100644
index 0000000..f3715be
--- /dev/null
+++ b/internal/storage/testdata/schema_v11.sql
@@ -0,0 +1,165 @@
+-- Schema version: 11
+-- Versioned; never silently rename columns.
+
+CREATE TABLE IF NOT EXISTS schema_version (
+ version INTEGER PRIMARY KEY,
+ applied_at TIMESTAMPTZ DEFAULT now()
+);
+
+-- Raw OTLP spans from Claude Code
+CREATE TABLE IF NOT EXISTS spans (
+ -- OTLP identity
+ trace_id VARCHAR NOT NULL,
+ span_id VARCHAR NOT NULL PRIMARY KEY,
+ parent_span_id VARCHAR,
+ name VARCHAR NOT NULL,
+
+ -- Timing
+ start_time TIMESTAMPTZ NOT NULL,
+ end_time TIMESTAMPTZ NOT NULL,
+
+ -- Service metadata
+ service_name VARCHAR,
+
+ -- Extracted high-cardinality keys (index targets)
+ session_id VARCHAR,
+ model VARCHAR,
+ tool_name VARCHAR,
+
+ -- Actor (person, agent or host) the span is attributed to: the actors.name
+ -- of the token that sent it, NULL when unauthenticated. Was user_id before v11.
+ actor_id VARCHAR,
+
+ -- OTLP span status: 0=UNSET, 1=OK, 2=ERROR
+ status_code TINYINT DEFAULT 0,
+
+ -- Token / cost counters
+ input_tokens INTEGER,
+ output_tokens INTEGER,
+ cache_read_tokens INTEGER,
+ cache_write_tokens INTEGER,
+ cost_usd DOUBLE,
+
+ -- Full attribute bag (for ad-hoc queries)
+ attributes JSON,
+ resource_attrs JSON,
+
+ ingested_at TIMESTAMPTZ DEFAULT now()
+);
+
+-- Migration v1 → v2: add status_code if upgrading an existing database.
+ALTER TABLE spans ADD COLUMN IF NOT EXISTS status_code TINYINT DEFAULT 0;
+
+-- Migration v2 → v3: add the attribution column (named user_id until v11).
+ALTER TABLE spans ADD COLUMN IF NOT EXISTS actor_id VARCHAR;
+
+-- Migration v9 → v10: drop the derived duration_ms column (ADR-0013). As a
+-- VIRTUAL generated column it took a logical slot but no storage slot, so every
+-- later column's logical index ran one ahead of its physical index and a bare
+-- `col = ` probed an unrelated index and matched nothing. Duration is
+-- computed where it is read.
+--
+-- DuckDB refuses to ALTER a table an index depends on, so the secondary indexes
+-- are dropped here and recreated below. Both statements are idempotent, so a
+-- re-apply of this file rebuilds the indexes but moves no row data.
+DROP INDEX IF EXISTS idx_spans_session_id;
+DROP INDEX IF EXISTS idx_spans_start_time;
+DROP INDEX IF EXISTS idx_spans_name;
+DROP INDEX IF EXISTS idx_spans_actor_id;
+ALTER TABLE spans DROP COLUMN IF EXISTS duration_ms;
+
+-- Indexes for dashboard hot paths (DuckDB ART indexes).
+CREATE INDEX IF NOT EXISTS idx_spans_session_id ON spans(session_id);
+CREATE INDEX IF NOT EXISTS idx_spans_start_time ON spans(start_time);
+CREATE INDEX IF NOT EXISTS idx_spans_name ON spans(name);
+CREATE INDEX IF NOT EXISTS idx_spans_actor_id ON spans(actor_id);
+
+-- Daily aggregates for long-term retention (schema version 1)
+CREATE TABLE IF NOT EXISTS daily_usage (
+ day DATE NOT NULL,
+ session_id VARCHAR,
+ model VARCHAR,
+ tool_name VARCHAR,
+ actor_id VARCHAR,
+ span_count BIGINT,
+ total_input_tokens BIGINT,
+ total_output_tokens BIGINT,
+ total_cache_read_tokens BIGINT,
+ total_cache_write_tokens BIGINT,
+ total_cost_usd DOUBLE,
+ total_duration_ms DOUBLE,
+ fail_count BIGINT,
+ PRIMARY KEY (day, session_id, model, tool_name)
+);
+
+-- Migration v2 → v3: add the attribution column to daily_usage (user_id until v11).
+ALTER TABLE daily_usage ADD COLUMN IF NOT EXISTS actor_id VARCHAR;
+
+-- Migration v7 → v8: preserve cache-token totals through roll-up.
+-- Additive, nullable, no default: rows rolled up before this migration stay NULL
+-- (honestly "unknown", not a fabricated 0); rows rolled up after get real sums.
+ALTER TABLE daily_usage ADD COLUMN IF NOT EXISTS total_cache_read_tokens BIGINT;
+ALTER TABLE daily_usage ADD COLUMN IF NOT EXISTS total_cache_write_tokens BIGINT;
+
+-- Migration v8 → v9: preserve duration and failure counts through roll-up.
+ALTER TABLE daily_usage ADD COLUMN IF NOT EXISTS total_duration_ms DOUBLE;
+ALTER TABLE daily_usage ADD COLUMN IF NOT EXISTS fail_count BIGINT;
+
+-- API tokens for OTLP ingest auth (schema version 4) — kept for upgrade safety, not used by new auth
+CREATE TABLE IF NOT EXISTS api_tokens (
+ id VARCHAR PRIMARY KEY,
+ name VARCHAR NOT NULL,
+ token_hash VARCHAR NOT NULL UNIQUE,
+ prefix VARCHAR NOT NULL,
+ created_at TIMESTAMPTZ DEFAULT now(),
+ last_used_at TIMESTAMPTZ
+);
+
+-- Named actors (people, agents, hosts) with always-visible plaintext tokens.
+-- Created as `users` in schema version 5, renamed to `actors` in version 11.
+CREATE TABLE IF NOT EXISTS actors (
+ id VARCHAR PRIMARY KEY,
+ name VARCHAR NOT NULL UNIQUE,
+ token VARCHAR NOT NULL UNIQUE,
+ created_at TIMESTAMPTZ DEFAULT now()
+);
+
+-- Runtime key/value settings (schema version 6)
+CREATE TABLE IF NOT EXISTS settings (
+ key VARCHAR PRIMARY KEY,
+ value VARCHAR NOT NULL,
+ updated_at TIMESTAMPTZ DEFAULT now()
+);
+
+-- Seed allow_anonymous=true (old "no tokens = open" default preserved)
+INSERT INTO settings (key, value) VALUES ('allow_anonymous', 'true') ON CONFLICT DO NOTHING;
+
+-- Migration v4→v5: backfill an actor row for each distinct span actor_id.
+-- Uses ON CONFLICT DO NOTHING on the UNIQUE name column to be idempotent.
+-- Token is 'cotel_' + 64 hex chars built from two md5 calls to avoid external deps.
+INSERT INTO actors (id, name, token)
+SELECT
+ uuid() AS id,
+ actor_id AS name,
+ 'cotel_' || md5(uuid()::VARCHAR) || md5(uuid()::VARCHAR) AS token
+FROM (SELECT DISTINCT actor_id FROM spans WHERE actor_id IS NOT NULL AND actor_id <> '') t
+WHERE NOT EXISTS (SELECT 1 FROM actors u WHERE u.name = t.actor_id)
+ AND t.actor_id <> '[deleted]';
+
+-- Migration v6 → v7: add deleted_at for soft-delete support.
+ALTER TABLE actors ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ DEFAULT NULL;
+
+INSERT INTO schema_version (version) VALUES (1) ON CONFLICT DO NOTHING;
+INSERT INTO schema_version (version) VALUES (2) ON CONFLICT DO NOTHING;
+INSERT INTO schema_version (version) VALUES (3) ON CONFLICT DO NOTHING;
+INSERT INTO schema_version (version) VALUES (4) ON CONFLICT DO NOTHING;
+INSERT INTO schema_version (version) VALUES (5) ON CONFLICT DO NOTHING;
+INSERT INTO schema_version (version) VALUES (6) ON CONFLICT DO NOTHING;
+INSERT INTO schema_version (version) VALUES (7) ON CONFLICT DO NOTHING;
+INSERT INTO schema_version (version) VALUES (8) ON CONFLICT DO NOTHING;
+INSERT INTO schema_version (version) VALUES (9) ON CONFLICT DO NOTHING;
+INSERT INTO schema_version (version) VALUES (10) ON CONFLICT DO NOTHING;
+-- v11 renames users → actors and user_id → actor_id. A rename cannot be written
+-- idempotently in SQL, so it is not in this file: migrateUsersToActors in
+-- duckdb.go runs it before this file is applied (ADR-0027).
+INSERT INTO schema_version (version) VALUES (11) ON CONFLICT DO NOTHING;
diff --git a/scripts/agent-set-cotel-token.sh b/scripts/agent-set-cotel-token.sh
index 4183537..815bd99 100755
--- a/scripts/agent-set-cotel-token.sh
+++ b/scripts/agent-set-cotel-token.sh
@@ -2,27 +2,26 @@
#
# agent-set-cotel-token.sh — give the running agent its own cotel telemetry token.
#
-# cotel attributes OTLP spans to an actor by the bearer token in
-# OTEL_EXPORTER_OTLP_HEADERS. If every Claude Code instance sends the same token,
-# all agents merge into one bucket. This script makes each agent self-attribute
-# by writing its OWN token into ITS OWN Paperclip adapter env, so every future
-# run exports telemetry under that agent's distinct cotel actor.
+# cotel attributes OTLP spans to an actor by its actor token. Paperclip sends one
+# company-wide OTLP destination and Authorization header (a cotel ingest key) for
+# every agent and strips any per-agent OTEL_* env (ADR-0028), so the agent's
+# identity travels separately: this script writes the agent's OWN actor token
+# into ITS OWN Paperclip adapter env as COTEL_ACTOR_TOKEN, and
+# scripts/otel-headers-helper.py (wired as Claude Code's otelHeadersHelper) sends
+# it as the X-Cotel-Actor-Token header. Without it the agent's spans are stored as
+# Anonymous.
#
# Why self-apply (not a central rollout): identical to the git-identity case —
# the Paperclip API redacts other agents' adapterConfig and rejects cross-agent
# edits (needs `agents:create`), and a blind cross-agent write cannot read and
# preserve another agent's secret env, so it would silently wipe secrets. Each
-# agent can read its own full config and merge the OTEL header in safely. See
+# agent can read its own full config and merge the variable in safely. See
# scripts/agent-set-git-identity.sh and docs/operations/agent-identity.md.
#
-# IMPORTANT — this sets ONLY the per-agent identity header. The shared,
-# identity-independent OTEL config (CLAUDE_CODE_ENABLE_TELEMETRY,
-# OTEL_TRACES_EXPORTER, OTEL_EXPORTER_OTLP_PROTOCOL,
-# OTEL_EXPORTER_OTLP_TRACES_ENDPOINT) stays in the global ~/.claude/settings.json
-# `env` block, which every Claude Code launch reads. The identity header must NOT
-# live there: settings.json `env` is applied at startup and OVERRIDES the
-# inherited per-agent process env, so a hardcoded header there clobbers this one.
-# (settings.json `env` is applied at startup and overrides the inherited per-agent process env.)
+# IMPORTANT — COTEL_ACTOR_TOKEN must live in the per-agent adapter env, never in a
+# shared settings.json `env` block: that block is applied at startup and
+# OVERRIDES the inherited per-agent process env, so every agent would claim the
+# same actor.
#
# The token cannot be derived — it is minted in the cotel dashboard
# (Actors -> Add actor, one actor per agent) and is a `cotel_<64 hex>` string. Pass
@@ -79,21 +78,27 @@ name = me.get("name") or "(unknown)"
ac = me.get("adapterConfig") or {}
env = dict(ac.get("env") or {}) # readable for SELF — preserve existing (incl. secrets)
-header = f"Authorization=Bearer {token}"
-
def current(k):
v = env.get(k)
return v.get("value") if isinstance(v, dict) else v
-if current("OTEL_EXPORTER_OTLP_HEADERS") == header:
- print(f"cotel token already set for {name} (token ...{token[-8:]}) — no change")
+# Since Paperclip v2026.1106 the per-agent OTEL_* env is stripped before every
+# run and the company-wide observability destination is applied instead
+# (ADR-0028). The agent's identity therefore travels as COTEL_ACTOR_TOKEN, which
+# scripts/otel-headers-helper.py turns into the X-Cotel-Actor-Token header. A
+# leftover OTEL_EXPORTER_OTLP_HEADERS is dropped: it is stripped anyway and only
+# misleads whoever reads the config.
+stale = "OTEL_EXPORTER_OTLP_HEADERS" in env
+if current("COTEL_ACTOR_TOKEN") == token and not stale:
+ print(f"cotel actor token already set for {name} (token ...{token[-8:]}) — no change")
sys.exit(0)
-env["OTEL_EXPORTER_OTLP_HEADERS"] = {"type": "plain", "value": header}
+env.pop("OTEL_EXPORTER_OTLP_HEADERS", None)
+env["COTEL_ACTOR_TOKEN"] = {"type": "plain", "value": token}
# Send ONLY env (the API shallow-merges top-level adapterConfig keys, and an
# env-only PATCH avoids the 403 that a full-adapterConfig self-PATCH triggers for
# managed-instruction agents). See agent-set-git-identity.sh for the full note.
call("PATCH", f"/api/agents/{agent_id}", {"adapterConfig": {"env": env}})
-print(f"set cotel token for {name} (token ...{token[-8:]}) — applies on the next run")
+print(f"set cotel actor token for {name} (token ...{token[-8:]}) — applies on the next run")
PY
diff --git a/scripts/otel-headers-helper.py b/scripts/otel-headers-helper.py
new file mode 100755
index 0000000..7f0c118
--- /dev/null
+++ b/scripts/otel-headers-helper.py
@@ -0,0 +1,122 @@
+#!/usr/bin/env python3
+#
+# otel-headers-helper.py — Claude Code `otelHeadersHelper` that adds the cotel
+# actor token to the OTLP headers a sender already has.
+#
+# Why it exists: when one OTLP destination and one set of headers is shared by
+# many senders (Paperclip's company-wide "Agent observability" setting applies
+# the same headers to every agent run), the shared `Authorization: Bearer
+# ` header authorizes the request but cannot say which actor sent
+# it. cotel reads the actor from a second header, `X-Cotel-Actor-Token`, and
+# this helper puts each sender's own actor token there from the env var
+# COTEL_ACTOR_TOKEN. See docs/operations/actors-and-auth.md ("Ingest keys") and
+# docs/decisions/0028-ingest-keys-and-actor-tokens.md.
+#
+# Wiring: in the settings.json that the agent's Claude Code reads
+# (e.g. ~/.claude/settings.json), set
+#
+# "otelHeadersHelper": "/path/to/otel-headers-helper.py"
+#
+# and give each agent its own COTEL_ACTOR_TOKEN in its process env. Do not put
+# COTEL_ACTOR_TOKEN in the settings.json `env` block: that block is shared by
+# every launch and would give all agents the same identity.
+#
+# Claude Code runs the helper at startup and again every 29 minutes
+# (CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS), only for the http/protobuf and
+# http/json protocols. How its output merges with the static
+# OTEL_EXPORTER_OTLP_*HEADERS env vars is not documented, so this helper prints
+# the COMPLETE header set itself:
+#
+# 1. OTEL_EXPORTER_OTLP_HEADERS, then OTEL_EXPORTER_OTLP_TRACES_HEADERS on top
+# (the per-signal value wins for the same header name, compared
+# case-insensitively). Both use the OTEL format: comma-separated
+# `key=value` pairs with percent-encoded values. Malformed entries are
+# skipped.
+# 2. If COTEL_ACTOR_TOKEN is non-empty, `X-Cotel-Actor-Token: `.
+#
+# Contract: if the helper fails or prints anything but a JSON object, Claude
+# Code stops exporting until it works again. So this script always prints
+# exactly one JSON object of string -> string to stdout and exits 0, even on an
+# unexpected error (it then prints whatever it had built, possibly `{}`).
+# Diagnostics go to stderr only, and header values are never printed there.
+#
+# Stdlib only; Python 3.9 or newer.
+
+import json
+import os
+import sys
+from urllib.parse import unquote
+
+ACTOR_HEADER = "X-Cotel-Actor-Token"
+_written = False
+
+
+def parse_otel_headers(raw):
+ """Parse an OTEL `key=value,key2=value2` string into (key, value) pairs."""
+ pairs = []
+ if not raw:
+ return pairs
+ for entry in raw.split(","):
+ if "=" not in entry:
+ continue
+ key, _, value = entry.partition("=")
+ key = key.strip()
+ if not key:
+ continue
+ value = unquote(value.strip()).strip()
+ pairs.append((key, value))
+ return pairs
+
+
+def put(headers, key, value):
+ """Set a header, replacing any existing one whose name differs only in case."""
+ for existing in [k for k in headers if k.lower() == key.lower()]:
+ del headers[existing]
+ headers[key] = value
+
+
+def build(headers):
+ for var in ("OTEL_EXPORTER_OTLP_HEADERS", "OTEL_EXPORTER_OTLP_TRACES_HEADERS"):
+ try:
+ for key, value in parse_otel_headers(os.environ.get(var, "")):
+ put(headers, key, value)
+ except Exception as exc: # keep going with what we have
+ print(f"otel-headers-helper: could not parse {var}: {type(exc).__name__}",
+ file=sys.stderr)
+ token = os.environ.get("COTEL_ACTOR_TOKEN", "").strip()
+ if token:
+ put(headers, ACTOR_HEADER, token)
+
+
+def main():
+ global _written
+ headers = {}
+ try:
+ build(headers)
+ except Exception as exc:
+ print(f"otel-headers-helper: unexpected error: {type(exc).__name__}",
+ file=sys.stderr)
+ try:
+ out = json.dumps({str(k): str(v) for k, v in headers.items()})
+ except Exception:
+ out = "{}"
+ try:
+ _written = True
+ sys.stdout.write(out + "\n")
+ sys.stdout.flush()
+ except Exception:
+ pass
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ main()
+ except BaseException:
+ if not _written:
+ try:
+ sys.stdout.write("{}\n")
+ sys.stdout.flush()
+ except BaseException:
+ pass
+ sys.exit(0)
diff --git a/scripts/otel-headers-helper_test.sh b/scripts/otel-headers-helper_test.sh
new file mode 100755
index 0000000..f6e0615
--- /dev/null
+++ b/scripts/otel-headers-helper_test.sh
@@ -0,0 +1,137 @@
+#!/usr/bin/env bash
+#
+# otel-headers-helper_test.sh — drive otel-headers-helper.py with controlled
+# environments. Claude Code stops exporting when the helper prints anything but
+# a JSON object, so every case also checks that stdout is exactly one JSON
+# object of string values and that the exit code is 0.
+
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+HELPER="$ROOT/scripts/otel-headers-helper.py"
+PASS=0
+FAIL=0
+
+fail() {
+ echo "FAIL: $*"
+ FAIL=$((FAIL + 1))
+}
+
+pass() {
+ echo "PASS: $*"
+ PASS=$((PASS + 1))
+}
+
+# Compares stdout to the wanted JSON object after normalising both, so key
+# order does not matter. Runs the helper with a clean environment plus the
+# given VAR=value pairs.
+expect() {
+ local name="$1" want="$2"
+ shift 2
+ local out rc
+ set +e
+ out="$(env -i PATH="$PATH" "$@" "$HELPER" 2>/dev/null)"
+ rc=$?
+ set -e
+ if [ "$rc" -ne 0 ]; then
+ fail "$name — exit $rc, want 0; stdout: $out"
+ return
+ fi
+ if ! printf '%s' "$out" | python3 -c '
+import json, sys
+obj = json.load(sys.stdin)
+assert isinstance(obj, dict), "not an object"
+assert all(isinstance(k, str) and isinstance(v, str) for k, v in obj.items()), "non-string entry"
+' 2>/dev/null; then
+ fail "$name — stdout is not a JSON object of strings: $out"
+ return
+ fi
+ if python3 -c '
+import json, sys
+sys.exit(0 if json.loads(sys.argv[1]) == json.loads(sys.argv[2]) else 1)
+' "$out" "$want"; then
+ pass "$name"
+ else
+ fail "$name — got $out, want $want"
+ fi
+}
+
+expect "no env prints an empty object" '{}'
+
+expect "generic headers only" \
+ '{"Authorization":"Bearer cotel_ik_abc","X-Extra":"1"}' \
+ OTEL_EXPORTER_OTLP_HEADERS='Authorization=Bearer cotel_ik_abc,X-Extra=1'
+
+expect "per-signal headers win on the same key" \
+ '{"Authorization":"Bearer traces","X-Extra":"1","X-Traces":"t"}' \
+ OTEL_EXPORTER_OTLP_HEADERS='Authorization=Bearer generic,X-Extra=1' \
+ OTEL_EXPORTER_OTLP_TRACES_HEADERS='Authorization=Bearer traces,X-Traces=t'
+
+expect "per-signal override ignores header-name case" \
+ '{"authorization":"Bearer traces"}' \
+ OTEL_EXPORTER_OTLP_HEADERS='Authorization=Bearer generic' \
+ OTEL_EXPORTER_OTLP_TRACES_HEADERS='authorization=Bearer traces'
+
+expect "values are percent-decoded" \
+ '{"Authorization":"Bearer abc"}' \
+ OTEL_EXPORTER_OTLP_TRACES_HEADERS='Authorization=Bearer%20abc'
+
+expect "whitespace around keys and values is trimmed" \
+ '{"Authorization":"Bearer abc","X-A":"b"}' \
+ OTEL_EXPORTER_OTLP_HEADERS=' Authorization = Bearer abc , X-A=b '
+
+expect "a value may contain '='" \
+ '{"X-Sig":"a=b=="}' \
+ OTEL_EXPORTER_OTLP_HEADERS='X-Sig=a=b=='
+
+expect "the actor token is added" \
+ '{"Authorization":"Bearer cotel_ik_abc","X-Cotel-Actor-Token":"cotel_123"}' \
+ OTEL_EXPORTER_OTLP_HEADERS='Authorization=Bearer cotel_ik_abc' \
+ COTEL_ACTOR_TOKEN=' cotel_123 '
+
+expect "the actor token replaces one already in the headers" \
+ '{"X-Cotel-Actor-Token":"cotel_mine"}' \
+ OTEL_EXPORTER_OTLP_HEADERS='x-cotel-actor-token=cotel_shared' \
+ COTEL_ACTOR_TOKEN='cotel_mine'
+
+expect "the actor token alone is enough" \
+ '{"X-Cotel-Actor-Token":"cotel_123"}' \
+ COTEL_ACTOR_TOKEN='cotel_123'
+
+expect "an empty actor token is ignored" \
+ '{"Authorization":"Bearer x"}' \
+ OTEL_EXPORTER_OTLP_HEADERS='Authorization=Bearer x' \
+ COTEL_ACTOR_TOKEN=' '
+
+expect "malformed entries are skipped" \
+ '{"Good":"1","Also":"2"}' \
+ OTEL_EXPORTER_OTLP_HEADERS='Good=1,noequals,,=novalue-key, ,Also=2'
+
+expect "an empty value is kept as an empty string" \
+ '{"X-Empty":""}' \
+ OTEL_EXPORTER_OTLP_HEADERS='X-Empty='
+
+expect "a broken percent escape is kept literally, not fatal" \
+ '{"X-Bad":"%zz"}' \
+ OTEL_EXPORTER_OTLP_HEADERS='X-Bad=%zz'
+
+# Nothing but the object may reach stdout, and token values must not be
+# echoed to stderr.
+set +e
+lines="$(env -i PATH="$PATH" COTEL_ACTOR_TOKEN=cotel_secret "$HELPER" 2>/dev/null | wc -l | tr -d ' ')"
+errout="$(env -i PATH="$PATH" COTEL_ACTOR_TOKEN=cotel_secret \
+ OTEL_EXPORTER_OTLP_HEADERS='Authorization=Bearer cotel_ik_secret' "$HELPER" 2>&1 >/dev/null)"
+set -e
+if [ "$lines" = "1" ]; then
+ pass "stdout is a single line"
+else
+ fail "stdout has $lines lines, want 1"
+fi
+case "$errout" in
+ *secret*) fail "a token value reached stderr: $errout" ;;
+ *) pass "no token value on stderr" ;;
+esac
+
+echo
+echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" -eq 0 ]