diff --git a/.github/workflows/go-backend.yml b/.github/workflows/go-backend.yml index a48fa82..2209268 100644 --- a/.github/workflows/go-backend.yml +++ b/.github/workflows/go-backend.yml @@ -29,6 +29,13 @@ jobs: go vet ./... - name: Integration and race tests run: backend/scripts/test-integration.sh + - name: Structured log collector compatibility + working-directory: backend + env: + GO_TEST_VECTOR_IMAGE: timberio/vector:0.61.0-debian@sha256:f6c23b5a7e16fb2838d33619ef7acf4bad2289a7cf22bc90efc2371f520c4ea2 + run: | + docker pull "$GO_TEST_VECTOR_IMAGE" + go test -race ./internal/logging -run '^TestVectorCollector$' - name: Output compatibility env: SESSION_SECRET: synthetic-ci-session diff --git a/backend/README.md b/backend/README.md index be3b573..85da97d 100644 --- a/backend/README.md +++ b/backend/README.md @@ -5,7 +5,7 @@ This branch includes `main` through `511dcd7`. Go now implements the 13 APIs added since the previous migration, along with paid hosting, bibliography preservation, account email preferences, access notifications, direct public GitHub submodules, and the mounted review-service capability endpoint. The current 127-route inventory and Node differential contracts are checked in CI. See [the alignment report](reports/main-alignment.json) for validation and remaining staging checks. Route coverage alone does not establish complete behavioral equivalence. -The migration branch also includes PR #953’s expiration emails and admin delivery history, with a Go implementation backed by the same collection. Hosting-quota failures no longer enter automatic retry loops. Open PR #956 still needs a Go logging adapter for its JSON collector; its operational stack has not been deployed. +The migration branch also includes PR #953’s expiration emails and admin delivery history, with a Go implementation backed by the same collection. Hosting-quota failures no longer enter automatic retry loops. Go emits structured JSON compatible with PR #956’s collector. The operational logging stack has not been deployed. This directory implements the API, authentication, repository processing, file serving, storage adapters and background jobs in Go. The existing browser application remains JavaScript. Node is used to build browser assets, run differential tests and perform offline data migration; it is absent from the runtime image. @@ -84,6 +84,12 @@ Exclude local database dumps and unrelated large directories from the build cont The separate `.github/workflows/go-backend.yml` workflow runs formatting, static checks, integration/race tests, output comparisons, vulnerability scanning and the image build. +## Structured logs + +Go writes JSON to stderr with fixed event names, severity, generated trace IDs, status codes and bounded diagnostic fields. Arbitrary messages, errors, URLs, repository identifiers, payloads and credentials are discarded before serialization. `LOG_LEVEL` keeps its existing behavior; `APP_RELEASE` accepts a 7–40 character lowercase Git SHA. Job trace IDs persist across retries, and originating request IDs propagate through the job record. Process heartbeats include RSS, the container memory limit and active requests. + +The collector policy and unmodified Vector sanitizer fixture are pinned to PR #956 commit `f084f5c`. `GO_TEST_VECTOR_IMAGE=timberio/vector:0.61.0-debian go test -race ./internal/logging` checks real Go output through Vector in a network-isolated container. CI uses the image digest from that PR. Updating the collector requires reviewing both the field allowlist and its privacy tests. Fixed Go ZIP stages and reasons remain in local JSON logs; the pinned collector discards those additional fields. The logging stack itself is not installed by this migration change, and aggregate queue-heartbeat output remains a follow-up to the existing admin queue metrics. + ## Configuration The backend reads environment variables, not `.env` files itself. Compose loads the environment file. Preserve the existing `SESSION_SECRET`, `CREDENTIAL_KEYS`, and `CREDENTIAL_ACTIVE_KEY_ID` to retain sessions and encrypted GitHub grants. It supports the existing MongoDB, Redis, OAuth, GitHub App and S3 variable names in `internal/server/config.go`. diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go index dbc4e11..20c215c 100644 --- a/backend/cmd/server/main.go +++ b/backend/cmd/server/main.go @@ -3,6 +3,7 @@ package main import ( "context" "github.com/tdurieux/anonymous_github/backend/internal/anonymize" + "github.com/tdurieux/anonymous_github/backend/internal/logging" "github.com/tdurieux/anonymous_github/backend/internal/server" "log/slog" "net/http" @@ -51,7 +52,7 @@ func configureLogging() { case "error": level = slog.LevelError } - slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: level}))) + slog.SetDefault(slog.New(logging.New(os.Stderr, level, os.Getenv("APP_RELEASE")))) } func run() int { configureLogging() @@ -85,6 +86,7 @@ func run() int { app.Close() } }() + slog.Info("process started", "module", "process") httpServer := &http.Server{Addr: config.Address, Handler: app, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 2 * time.Minute, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 32 * 1024} drained, err = serveAndDrain(ctx, httpServer, app.RunJobs, 30*time.Second) if err != nil { diff --git a/backend/internal/logging/collector_test.go b/backend/internal/logging/collector_test.go new file mode 100644 index 0000000..f9d4b92 --- /dev/null +++ b/backend/internal/logging/collector_test.go @@ -0,0 +1,74 @@ +package logging + +import ( + "bytes" + "encoding/json" + "log/slog" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// Runs the unmodified PR #956 collector against actual Go log records. +func TestVectorCollector(t *testing.T) { + image := os.Getenv("GO_TEST_VECTOR_IMAGE") + if image == "" { + t.Skip("set GO_TEST_VECTOR_IMAGE to run the isolated collector") + } + var records bytes.Buffer + logger := slog.New(New(&records, slog.LevelInfo, "abcdef123")) + logger.Info("request", "requestId", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "route", "/api/repo/:id/file/:path", "status", 200, "ms", 42, "stages", map[string]float64{"upstream": 12}) + logger.With("service", "worker", "jobId", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb").Error("job failed", "queue", "download", "code", "quota_exceeded", "attempt", 2, "error", "secret-repository") + logger.Info("process heartbeat", "rss", 123456, "memoryRatio", 0.25, "uptime", 30) + dir := t.TempDir() + program, err := os.ReadFile("testdata/collector.vrl") + if err != nil { + t.Fatal(err) + } + if err = os.WriteFile(filepath.Join(dir, "collector.vrl"), append(program, []byte("\nencode_json(.)\n")...), 0600); err != nil { + t.Fatal(err) + } + var input bytes.Buffer + for _, line := range strings.Split(strings.TrimSpace(records.String()), "\n") { + raw, _ := json.Marshal(map[string]any{"log": line, "attrs": map[string]any{"tag": "api"}}) + if err = json.NewEncoder(&input).Encode(map[string]any{"file": "/host/docker/fixture/fixture-json.log", "message": string(raw)}); err != nil { + t.Fatal(err) + } + } + if err = os.WriteFile(filepath.Join(dir, "input.jsonl"), input.Bytes(), 0600); err != nil { + t.Fatal(err) + } + command := exec.CommandContext(t.Context(), "docker", "run", "--rm", "--network", "none", "-e", "VECTOR_LOG=error", "--user", "0:0", "-v", dir+":/fixture:ro", image, "vrl", "-p", "/fixture/collector.vrl", "-i", "/fixture/input.jsonl") + output, err := command.Output() + if err != nil { + t.Fatalf("%v: %s", err, output) + } + decoder := json.NewDecoder(bytes.NewReader(output)) + for i, event := range []string{"request_completed", "job_failed", "process_heartbeat"} { + var row map[string]any + var encoded string + if err = decoder.Decode(&encoded); err == nil { + err = json.Unmarshal([]byte(encoded), &row) + } + if err != nil { + t.Fatalf("%v: %s", err, output) + } + if row["event"] != event { + t.Fatal(row) + } + if i == 0 && (row["route"] != "/api/repo/:id/file/:path" || row["stage_upstream_ms"] != float64(12) || row["requestId"] == nil) { + t.Fatal(row) + } + if i == 1 && (row["service"] != "worker" || row["errorCode"] != "quota_exceeded" || row["severity"] != "error" || row["jobId"] == nil) { + t.Fatal(row) + } + if i == 2 && row["memoryRatio"] != 0.25 { + t.Fatal(row) + } + } + if strings.Contains(string(output), "secret") { + t.Fatal(string(output)) + } +} diff --git a/backend/internal/logging/handler.go b/backend/internal/logging/handler.go new file mode 100644 index 0000000..046fe67 --- /dev/null +++ b/backend/internal/logging/handler.go @@ -0,0 +1,159 @@ +// Package logging emits only collector-approved diagnostics. Messages, errors, +// URLs and arbitrary attributes are never serialized, even in development. +package logging + +import ( + "context" + _ "embed" + "encoding/json" + "io" + "log/slog" + "math" + "regexp" + "slices" + "strings" + + "github.com/google/uuid" +) + +//go:embed policy.json +var policyJSON []byte + +var policy struct { + Events map[string]string `json:"events"` + Allowed map[string][]string `json:"allowed"` + Numbers []string `json:"numbers"` +} +var traceID = regexp.MustCompile(`^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$`) +var releaseID = regexp.MustCompile(`^[a-f0-9]{7,40}$`) + +func init() { + if err := json.Unmarshal(policyJSON, &policy); err != nil { + panic(err) + } +} + +type Handler struct { + output slog.Handler + attrs []slog.Attr + grouped bool + instance, release string +} + +func New(w io.Writer, level slog.Leveler, release string) *Handler { + if !releaseID.MatchString(release) { + release = "unknown" + } + output := slog.NewJSONHandler(w, &slog.HandlerOptions{Level: level, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { + switch a.Key { + case slog.TimeKey: + a.Key = "timestamp" + case slog.LevelKey: + return slog.String("severity", strings.ToLower(a.Value.String())) + case slog.MessageKey: + a.Key = "message" + } + return a + }}) + return &Handler{output: output, instance: uuid.NewString(), release: release} +} +func (h *Handler) Enabled(ctx context.Context, level slog.Level) bool { + return h.output.Enabled(ctx, level) +} +func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler { + copy := *h + if !h.grouped { + copy.attrs = append(slices.Clone(h.attrs), attrs...) + } + return © +} +func (h *Handler) WithGroup(name string) slog.Handler { + copy := *h + if name != "" { + copy.grouped = true + } + return © +} +func (h *Handler) Handle(ctx context.Context, r slog.Record) error { + event := policy.Events[r.Message] + if event == "" { + event = "application_log" + } + out := slog.NewRecord(r.Time, r.Level, event, 0) + fields := map[string]slog.Value{} + add := func(a slog.Attr) { + // Do not Resolve LogValuers or format errors/Stringers: those may expose + // arbitrary provider data or execute user-defined code. + if a.Value.Kind() == slog.KindString { + key, value := a.Key, a.Value.String() + switch key { + case "code", "error": + key = "errorCode" + case "hostname": + key = "upstreamHost" + if !slices.Contains([]string{"github.com", "api.github.com", "codeload.github.com", "raw.githubusercontent.com", "media.githubusercontent.com"}, value) { + value = "other" + } + fields[key] = slog.StringValue(value) + return + case "requestId", "jobId", "deliveryId": + if traceID.MatchString(value) { + fields[key] = slog.StringValue(value) + } + return + case "stage", "module", "route", "method", "queue", "outcome", "reason", "phase", "webhookEvent", "errorCode": + case "service": + if slices.Contains([]string{"api", "streamer", "worker"}, value) { + fields[key] = slog.StringValue(value) + } + return + default: + return + } + if slices.Contains(policy.Allowed[key], value) { + fields[key] = slog.StringValue(value) + } + return + } + if slices.Contains(policy.Numbers, a.Key) && finite(a.Value) { + fields[a.Key] = a.Value + } + if a.Key == "stages" && a.Value.Kind() == slog.KindAny { + if stages, ok := a.Value.Any().(map[string]float64); ok { + for key, value := range stages { + key = "stage_" + key + "_ms" + if slices.Contains(policy.Numbers, key) && !math.IsNaN(value) && !math.IsInf(value, 0) { + fields[key] = slog.Float64Value(value) + } + } + } + } + } + for _, a := range h.attrs { + add(a) + } + if !h.grouped { + r.Attrs(func(a slog.Attr) bool { add(a); return true }) + } + if _, ok := fields["service"]; !ok { + fields["service"] = slog.StringValue("api") + } + // Callers cannot override event or process identity through attributes. + fields["event"] = slog.StringValue(event) + fields["instance"] = slog.StringValue(h.instance) + fields["release"] = slog.StringValue(h.release) + for key, value := range fields { + out.AddAttrs(slog.Attr{Key: key, Value: value}) + } + return h.output.Handle(ctx, out) +} +func finite(v slog.Value) bool { + switch v.Kind() { + case slog.KindInt64, slog.KindUint64: + return true + case slog.KindFloat64: + return !math.IsNaN(v.Float64()) && !math.IsInf(v.Float64(), 0) + default: + return false + } +} diff --git a/backend/internal/logging/handler_test.go b/backend/internal/logging/handler_test.go new file mode 100644 index 0000000..74aa761 --- /dev/null +++ b/backend/internal/logging/handler_test.go @@ -0,0 +1,107 @@ +package logging + +import ( + "bytes" + "encoding/json" + "log/slog" + "math" + "strings" + "sync" + "testing" +) + +type forbiddenValue struct{} + +func (forbiddenValue) LogValue() slog.Value { panic("must not resolve user values") } +func (forbiddenValue) String() string { panic("must not format user values") } + +func TestPrivateDataNeverSerialized(t *testing.T) { + var b bytes.Buffer + logger := slog.New(New(&b, slog.LevelDebug, "secret-release")) + logger.With("token", "secret-token", "requestId", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").Error("https://private.example/secret-repo", + "error", "secret-error", "url", "https://private.example/secret", "body", forbiddenValue{}, "ms", forbiddenValue{}, + "route", "/api/repo/secret-name", "code", "quota_exceeded", "status", 402, "severity", "debug", "instance", "secret-instance", + "stages", map[string]float64{"upstream": 2.5, "secret-stage": 9, "repository": math.Inf(1)}) + if strings.Contains(b.String(), "secret") || strings.Contains(b.String(), "private.example") { + t.Fatal(b.String()) + } + var record map[string]any + if err := json.Unmarshal(b.Bytes(), &record); err != nil { + t.Fatal(err) + } + if record["event"] != "application_log" || record["severity"] != "error" || record["errorCode"] != "quota_exceeded" || record["status"] != float64(402) || record["stage_upstream_ms"] != 2.5 || record["requestId"] == nil { + t.Fatal(record) + } + for _, key := range []string{"route", "ms", "stage_repository_ms", "body", "url", "token"} { + if record[key] != nil { + t.Fatal(key, record) + } + } +} + +func TestCollectorFieldsAndGroups(t *testing.T) { + var b bytes.Buffer + logger := slog.New(New(&b, slog.LevelInfo, "abcdef123")) + logger.Debug("request", "status", 200) + logger.With("service", "worker", "queue", "download").Info("job started", "attempt", 2, "jobId", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb") + logger.With("method", "GET").WithGroup("private").With("status", 999).Info("request", "route", "/api/repo/:id/file/:path", "status", 400) + rows := strings.Split(strings.TrimSpace(b.String()), "\n") + if len(rows) != 2 { + t.Fatal(b.String()) + } + for i, line := range rows { + var r map[string]any + if err := json.Unmarshal([]byte(line), &r); err != nil { + t.Fatal(err) + } + if r["release"] != "abcdef123" || !traceID.MatchString(r["instance"].(string)) || r["timestamp"] == nil { + t.Fatal(r) + } + if i == 0 && (r["event"] != "job_started" || r["service"] != "worker" || r["attempt"] != float64(2) || r["queue"] != "download") { + t.Fatal(r) + } + if i == 1 && (r["method"] != "GET" || r["status"] != nil || r["route"] != nil) { + t.Fatal(r) + } + } +} + +func TestConcurrentRecordsRemainJSON(t *testing.T) { + var b bytes.Buffer + logger := slog.New(New(&b, slog.LevelInfo, "")) + var workers sync.WaitGroup + for i := 0; i < 20; i++ { + workers.Add(1) + go func() { + defer workers.Done() + logger.With("method", "GET").Info("request", "route", "/healthcheck", "status", 200) + }() + } + workers.Wait() + rows := strings.Split(strings.TrimSpace(b.String()), "\n") + if len(rows) != 20 { + t.Fatal(len(rows)) + } + for _, row := range rows { + var record map[string]any + if err := json.Unmarshal([]byte(row), &record); err != nil { + t.Fatal(err) + } + if record["event"] != "request_completed" || record["route"] != "/healthcheck" { + t.Fatal(record) + } + } +} + +func TestZIPFailureKeepsFixedDiagnostics(t *testing.T) { + var output bytes.Buffer + logger := slog.New(New(&output, slog.LevelInfo, "")) + logger.Warn("ZIP transfer stopped", "stage", "authorization", "reason", "client_cancelled") + var row map[string]any + if err := json.Unmarshal(output.Bytes(), &row); err != nil { + t.Fatal(err) + } + if row["stage"] != "authorization" || row["reason"] != "client_cancelled" || row["event"] != "zip_stream_failed" { + t.Fatal(row) + } +} diff --git a/backend/internal/logging/policy.json b/backend/internal/logging/policy.json new file mode 100644 index 0000000..01487e5 --- /dev/null +++ b/backend/internal/logging/policy.json @@ -0,0 +1,692 @@ +{ + "source": "PR #956 f084f5cbfc7b328a04b4e7e859ce9fa224c605c4", + "events": { + "PR comments 404, continuing without them": "pr_comments_404_continuing_without_them", + "S3 body stream error": "s3_body_stream_error", + "account removed": "account_removed", + "billing maintenance failed": "billing_maintenance_failed", + "billing reconciliation deferred": "billing_reconciliation_deferred", + "billing requires attention": "billing_requires_attention", + "billing worker failed": "billing_worker_failed", + "blob API failed, falling back to raw URL": "blob_api_failed_falling_back_to_raw_url", + "branch not found": "branch_not_found", + "cache removal failed": "cache_removal_failed", + "cache removed": "cache_removed", + "checking repository status and unused repositories": "checking_repository_status_and_unused_repositories", + "cleared lock for active job": "cleared_lock_for_active_job", + "conference expire failed": "conference_expire_failed", + "content expiration failed": "content_expiration_failed", + "daily stats snapshot failed": "daily_stats_snapshot_failed", + "daily stats snapshot stored": "daily_stats_snapshot_stored", + "download completed": "download_completed", + "download start": "download_start", + "downloadFile failed": "downloadfile_failed", + "downloaded": "downloaded", + "downloading file": "downloading_file", + "downloading gist": "downloading_gist", + "downloading pull request": "downloading_pull_request", + "downloading via raw URL (LFS)": "downloading_via_raw_url_lfs", + "duplicate Stripe customer requires review": "duplicate_stripe_customer_requires_review", + "ensureTodaySnapshot failed": "ensuretodaysnapshot_failed", + "error log redis connect failed": "error_log_redis_connect_failed", + "expired repository cleanup failed": "expired_repository_cleanup_failed", + "failed removal recovery failed": "failed_removal_recovery_failed", + "failed to persist ERROR status": "failed_to_persist_error_status", + "failed to record repository removal error": "failed_to_record_repository_removal_error", + "getToken": "gettoken", + "github primary rate limit hit": "github_primary_rate_limit_hit", + "github secondary rate limit hit": "github_secondary_rate_limit_hit", + "grant revocation failed": "grant_revocation_failed", + "initial repository status check failed": "initial_repository_status_check_failed", + "job completed": "job_completed", + "job stalled": "job_stalled", + "job started": "job_started", + "lastUsedAt update failed": "lastusedat_update_failed", + "login-token failed": "login_token_failed", + "login-token req.login failed": "login_token_req_login_failed", + "logout after account removal failed": "logout_after_account_removal_failed", + "logout failed": "logout_failed", + "lookup failed": "lookup_failed", + "markErrorIfInFlight failed": "markerrorifinflight_failed", + "markErrorIfRemoving failed": "markerrorifremoving_failed", + "metadata cleanup complete": "metadata_cleanup_complete", + "metadata cleanup deferred": "metadata_cleanup_deferred", + "owner access alert reset unavailable": "owner_access_alert_reset_unavailable", + "owner access email accepted": "owner_access_email_accepted", + "owner access email audit unavailable": "owner_access_email_audit_unavailable", + "owner access email claim cleanup unavailable": "owner_access_email_claim_cleanup_unavailable", + "owner access email deferred recovery unavailable": "owner_access_email_deferred_recovery_unavailable", + "owner access email delivery failed": "owner_access_email_delivery_failed", + "owner access email preparation cleanup unavailable": "owner_access_email_preparation_cleanup_unavailable", + "owner access email recovery recorded": "owner_access_email_recovery_recorded", + "owner access email recovery unavailable": "owner_access_email_recovery_unavailable", + "owner access email result reconciliation required": "owner_access_email_result_reconciliation_required", + "owner access email unavailable": "owner_access_email_unavailable", + "process fatal error": "process_fatal_error", + "process heartbeat": "process_heartbeat", + "process started": "process_started", + "progress": "progress", + "queue heartbeat": "queue_heartbeat", + "queued for download": "queued_for_download", + "rate limit gate active, delaying job before work": "rate_limit_gate_active_delaying_job_before_work", + "rate limit gate set": "rate_limit_gate_set", + "rate-limited, delaying job": "rate_limited_delaying_job", + "recover failed": "recover_failed", + "recoverStuckPreparing failed": "recoverstuckpreparing_failed", + "recoverStuckRemoving failed": "recoverstuckremoving_failed", + "recovered expired repository cleanup": "recovered_expired_repository_cleanup", + "recovered file from truncated tree": "recovered_file_from_truncated_tree", + "recovered file invalidation failed": "recovered_file_invalidation_failed", + "recovered stuck repo": "recovered_stuck_repo", + "redis client error": "redis_client_error", + "redis rate limit gate written": "redis_rate_limit_gate_written", + "rejected upstream download destination": "rejected_upstream_download_destination", + "removal failed": "removal_failed", + "removal recovery failed": "removal_recovery_failed", + "removeCache save failed": "removecache_save_failed", + "removed cache for unused repository": "removed_cache_for_unused_repository", + "removing cache": "removing_cache", + "removing repository": "removing_repository", + "repo claimed": "repo_claimed", + "repository cache removal failed": "repository_cache_removal_failed", + "repository expiration failed": "repository_expiration_failed", + "repository expired": "repository_expired", + "repository removal failed": "repository_removal_failed", + "repository removed": "repository_removed", + "requeued failed removal": "requeued_failed_removal", + "requeued interrupted removal": "requeued_interrupted_removal", + "reset": "reset", + "retired tree cleanup deferred": "retired_tree_cleanup_deferred", + "retired tree cleanup failed": "retired_tree_cleanup_failed", + "running daily stats snapshot": "running_daily_stats_snapshot", + "send failed": "send_failed", + "server started": "server_started", + "source stream failed; cache write discarded": "source_stream_failed_cache_write_discarded", + "staged tree cleanup failed": "staged_tree_cleanup_failed", + "staged tree completion deferred": "staged_tree_completion_deferred", + "streamer fetch failed": "streamer_fetch_failed", + "streamer started": "streamer_started", + "streamer startup failed": "streamer_startup_failed", + "streamer zip fetch failed": "streamer_zip_fetch_failed", + "temporary storage cleanup deferred": "temporary_storage_cleanup_deferred", + "token refresh failed; backing off": "token_refresh_failed_backing_off", + "up to date": "up_to_date", + "update queued": "update_queued", + "verify failed": "verify_failed", + "waiting for rate limit gate": "waiting_for_rate_limit_gate", + "webhook processing failed": "webhook_processing_failed", + "write failed": "write_failed", + "zip stream failed": "zip_stream_failed", + "request": "request_completed", + "slow request": "request_slow", + "request interrupted": "request_cancelled", + "job failed": "job_failed", + "configuration rejected": "process_fatal_error", + "startup failed": "process_fatal_error", + "server stopped": "process_fatal_error", + "request panicked": "application_log", + "ZIP transfer stopped": "zip_stream_failed" + }, + "allowed": { + "s": [ + "E", + "F" + ], + "limit_req_status": [ + "PASSED", + "DELAYED", + "REJECTED", + "DELAYED_DRY_RUN", + "REJECTED_DRY_RUN" + ], + "severity": [ + "debug", + "info", + "warn", + "error" + ], + "event": [ + "account_removed", + "application_log", + "billing_maintenance_failed", + "billing_reconciliation_deferred", + "billing_requires_attention", + "billing_worker_failed", + "blob_api_failed_falling_back_to_raw_url", + "branch_not_found", + "cache_removal_failed", + "cache_removed", + "checking_repository_status_and_unused_repositories", + "cleared_lock_for_active_job", + "conference_expire_failed", + "content_expiration_failed", + "daily_stats_snapshot_failed", + "daily_stats_snapshot_stored", + "download_completed", + "download_start", + "downloaded", + "downloadfile_failed", + "downloading_file", + "downloading_gist", + "downloading_pull_request", + "downloading_via_raw_url_lfs", + "duplicate_stripe_customer_requires_review", + "ensuretodaysnapshot_failed", + "error_log_redis_connect_failed", + "expired_repository_cleanup_failed", + "failed_removal_recovery_failed", + "failed_to_persist_error_status", + "failed_to_record_repository_removal_error", + "gettoken", + "github_primary_rate_limit_hit", + "github_secondary_rate_limit_hit", + "grant_revocation_failed", + "initial_repository_status_check_failed", + "job_completed", + "job_failed", + "job_stalled", + "job_started", + "lastusedat_update_failed", + "login_token_failed", + "login_token_req_login_failed", + "logout_after_account_removal_failed", + "logout_failed", + "lookup_failed", + "markerrorifinflight_failed", + "markerrorifremoving_failed", + "metadata_cleanup_complete", + "metadata_cleanup_deferred", + "owner_access_alert_reset_unavailable", + "owner_access_email_accepted", + "owner_access_email_audit_unavailable", + "owner_access_email_claim_cleanup_unavailable", + "owner_access_email_deferred_recovery_unavailable", + "owner_access_email_delivery_failed", + "owner_access_email_preparation_cleanup_unavailable", + "owner_access_email_recovery_recorded", + "owner_access_email_recovery_unavailable", + "owner_access_email_result_reconciliation_required", + "owner_access_email_unavailable", + "pr_comments_404_continuing_without_them", + "process_fatal_error", + "process_heartbeat", + "process_started", + "progress", + "queue_heartbeat", + "queued_for_download", + "rate_limit_gate_active_delaying_job_before_work", + "rate_limit_gate_set", + "rate_limited_delaying_job", + "recover_failed", + "recovered_expired_repository_cleanup", + "recovered_file_from_truncated_tree", + "recovered_file_invalidation_failed", + "recovered_stuck_repo", + "recoverstuckpreparing_failed", + "recoverstuckremoving_failed", + "redis_client_error", + "redis_rate_limit_gate_written", + "rejected_upstream_download_destination", + "removal_failed", + "removal_recovery_failed", + "removecache_save_failed", + "removed_cache_for_unused_repository", + "removing_cache", + "removing_repository", + "repo_claimed", + "repository_cache_removal_failed", + "repository_expiration_failed", + "repository_expired", + "repository_removal_failed", + "repository_removed", + "request_cancelled", + "request_completed", + "request_slow", + "requeued_failed_removal", + "requeued_interrupted_removal", + "reset", + "retired_tree_cleanup_deferred", + "retired_tree_cleanup_failed", + "running_daily_stats_snapshot", + "s3_body_stream_error", + "send_failed", + "server_started", + "source_stream_failed_cache_write_discarded", + "staged_tree_cleanup_failed", + "staged_tree_completion_deferred", + "streamer_fetch_failed", + "streamer_started", + "streamer_startup_failed", + "streamer_zip_fetch_failed", + "temporary_storage_cleanup_deferred", + "token_refresh_failed_backing_off", + "up_to_date", + "update_queued", + "verify_failed", + "waiting_for_rate_limit_gate", + "webhook_log", + "webhook_processing_failed", + "write_failed", + "zip_stream_failed" + ], + "errorCode": [ + "ABORT_ERR", + "ECONNREFUSED", + "ECONNRESET", + "ENOTFOUND", + "EPIPE", + "ETIMEDOUT", + "billing_address_missing", + "billing_city_missing", + "billing_country_missing", + "billing_email_missing", + "billing_missing", + "billing_name_missing", + "billing_zip_missing", + "branch_not_found", + "branch_not_specified", + "cache_busy", + "cache_miss", + "cannot_coauthor_self", + "commit_not_specified", + "conf_end_date_invalid", + "conf_end_date_missing", + "conf_id_missing", + "conf_id_used", + "conf_name_missing", + "conf_not_activated", + "conf_not_found", + "conf_start_date_invalid", + "conf_start_date_missing", + "conference_not_found", + "connection_changed", + "download_not_enabled", + "expiration_limit_reached", + "file_listing_too_large", + "file_not_accessible", + "file_not_found", + "file_not_supported", + "file_too_big", + "folder_not_supported", + "gistId_already_used", + "gistId_not_specified", + "gist_expired", + "gist_not_found", + "gist_not_ready", + "github_app_access_required", + "github_app_reconnect_required", + "github_identity_mismatch", + "github_rate_limit_exceeded", + "github_token_invalid", + "github_user_not_found", + "invalid_commit_format", + "invalid_cursor", + "invalid_file_path", + "invalid_gistId", + "invalid_path", + "invalid_plan", + "invalid_preserve_files_format", + "invalid_project_name", + "invalid_pullRequestId", + "invalid_repo", + "invalid_repoId", + "invalid_request", + "invalid_settings", + "invalid_signature", + "invalid_sort", + "invalid_status", + "invalid_terms_format", + "invalid_token_id", + "invalid_token_options", + "is_removed", + "not_authorized", + "not_connected", + "options_not_provided", + "page_not_activated", + "page_not_supported_on_different_branch", + "path_not_defined", + "path_not_specified", + "pullRequestId_already_used", + "pullRequestId_is_not_a_number", + "pullRequestId_not_specified", + "pull_request_expired", + "pull_request_not_found", + "pull_request_not_ready", + "token_refresh_failed", + "quota_exceeded", + "rate_limited", + "readme_not_available", + "repoId_already_used", + "repoId_not_defined", + "repoUrl_not_defined", + "repo_access_limited", + "repo_empty", + "repo_not_accessible", + "repo_not_found", + "repo_saml_enforcement", + "repository_archived", + "repository_changed", + "repository_expired", + "repository_job_cancelled", + "repository_not_found", + "repository_not_ready", + "repository_not_specified", + "repository_tree_incomplete", + "repository_tree_too_large", + "s3_config_not_provided", + "source_not_provided", + "storage_delete_failed", + "storage_write_size_mismatch", + "submodule_not_available", + "terms_not_specified", + "token_expired", + "token_limit_reached", + "unable_to_connect_user", + "unable_to_download", + "upstream_error", + "upstream_timeout", + "user_not_found", + "username_not_defined", + "webhook_processing_failed" + ], + "module": [ + "admin", + "anonymized-file", + "auth", + "billing", + "dailyStats", + "file-tree", + "fs", + "gh-stream", + "gist", + "github", + "github-app-webhook", + "owner-notifications", + "process", + "pull-request", + "queue", + "queue:cache", + "queue:download", + "queue:remove", + "repository", + "repository-public", + "requests", + "route", + "route:repo", + "s3", + "schedule", + "server", + "streamer", + "temporary-storage", + "token-auth", + "user", + "zip-stream" + ], + "reason": [ + "protocol", + "credentials", + "port", + "host", + "request_deadline", + "client_cancelled", + "truncated_source", + "io_timeout", + "invalid_archive_trailer", + "invalid_archive_path", + "invalid_archive_root", + "unsupported_archive_entry", + "invalid_or_duplicate_archive_path", + "duplicate_archive_metadata", + "archive_metadata_missing", + "archive_entry_size_mismatch", + "archive_stream_failed", + "ABORT_ERR", + "ECONNREFUSED", + "ECONNRESET", + "ENOTFOUND", + "EPIPE", + "ETIMEDOUT", + "billing_address_missing", + "billing_city_missing", + "billing_country_missing", + "billing_email_missing", + "billing_missing", + "billing_name_missing", + "billing_zip_missing", + "branch_not_found", + "branch_not_specified", + "cache_busy", + "cache_miss", + "cannot_coauthor_self", + "commit_not_specified", + "conf_end_date_invalid", + "conf_end_date_missing", + "conf_id_missing", + "conf_id_used", + "conf_name_missing", + "conf_not_activated", + "conf_not_found", + "conf_start_date_invalid", + "conf_start_date_missing", + "conference_not_found", + "connection_changed", + "download_not_enabled", + "expiration_limit_reached", + "file_listing_too_large", + "file_not_accessible", + "file_not_found", + "file_not_supported", + "file_too_big", + "folder_not_supported", + "gistId_already_used", + "gistId_not_specified", + "gist_expired", + "gist_not_found", + "gist_not_ready", + "github_app_access_required", + "github_app_reconnect_required", + "github_identity_mismatch", + "github_rate_limit_exceeded", + "github_token_invalid", + "github_user_not_found", + "invalid_commit_format", + "invalid_cursor", + "invalid_file_path", + "invalid_gistId", + "invalid_path", + "invalid_plan", + "invalid_preserve_files_format", + "invalid_project_name", + "invalid_pullRequestId", + "invalid_repo", + "invalid_repoId", + "invalid_request", + "invalid_settings", + "invalid_signature", + "invalid_sort", + "invalid_status", + "invalid_terms_format", + "invalid_token_id", + "invalid_token_options", + "is_removed", + "not_authorized", + "not_connected", + "options_not_provided", + "page_not_activated", + "page_not_supported_on_different_branch", + "path_not_defined", + "path_not_specified", + "pullRequestId_already_used", + "pullRequestId_is_not_a_number", + "pullRequestId_not_specified", + "pull_request_expired", + "pull_request_not_found", + "pull_request_not_ready", + "token_refresh_failed", + "quota_exceeded", + "rate_limited", + "readme_not_available", + "repoId_already_used", + "repoId_not_defined", + "repoUrl_not_defined", + "repo_access_limited", + "repo_empty", + "repo_not_accessible", + "repo_not_found", + "repo_saml_enforcement", + "repository_archived", + "repository_changed", + "repository_expired", + "repository_job_cancelled", + "repository_not_found", + "repository_not_ready", + "repository_not_specified", + "repository_tree_incomplete", + "repository_tree_too_large", + "s3_config_not_provided", + "source_not_provided", + "storage_delete_failed", + "storage_write_size_mismatch", + "submodule_not_available", + "terms_not_specified", + "token_expired", + "token_limit_reached", + "unable_to_connect_user", + "unable_to_download", + "upstream_error", + "upstream_timeout", + "user_not_found", + "username_not_defined", + "webhook_processing_failed" + ], + "phase": [ + "parse", + "find_grant_owners", + "reconcile_grant", + "persist_installation_block", + "reconcile_installation" + ], + "webhookEvent": [ + "github_app_authorization", + "installation", + "installation_repositories" + ], + "upstreamHost": [ + "github.com", + "api.github.com", + "codeload.github.com", + "raw.githubusercontent.com", + "media.githubusercontent.com", + "other" + ], + "queue": [ + "download", + "remove", + "cache" + ], + "outcome": [ + "completed", + "interrupted" + ], + "method": [ + "GET", + "HEAD", + "POST", + "PUT", + "PATCH", + "DELETE", + "OPTIONS", + "OTHER" + ], + "route": [ + "/", + "other", + "/dashboard", + "/anonymize", + "/healthcheck", + "/api/healthcheck", + "/api", + "/api/download", + "/api/stat", + "/api/stat/history", + "/api/options", + "/api/message", + "/api/user", + "/api/user/quota", + "/api/user/dashboard", + "/api/repo", + "/api/anonymize-preview", + "/api/admin/overview", + "/api/admin/performance", + "/api/admin/errors", + "/api/admin/errors/stats", + "/api/admin/queues", + "/api/admin/queues/metrics", + "/github/app/webhook", + "/api/repo/:repoId", + "/api/repo/:repoId/file/:path", + "/api/repo/:repoId/files", + "/api/repo/:repoId/files/counts", + "/api/repo/:repoId/files/search", + "/api/repo/:repoId/zip", + "/api/repo/:repoId/options", + "/api/repo/:repoId/refresh", + "/api/repo/:repoId/coauthors", + "/api/repo/:repoId/extend", + "/api/repo/:owner/:repo/readme", + "/api/repo/:owner/:repo/branches", + "/w/:repoId/:path", + "/r/:repoId/:path", + "/api/pr/:id/:path", + "/api/gist/:id/:path", + "/assets/:path", + "/github/:action", + "/api/admin/:action", + "/api/user/:action", + "/api/repo/:id/file/:path", + "/api/repo/:id/files/counts", + "/api/repo/:id/files/search", + "/api/repo/:id/files", + "/api/repo/:id/zip", + "/api/repo/:id", + "/viewer/:id/:path" + ], + "stage": [ + "prepare", + "authorization", + "output", + "finalize" + ] + }, + "numbers": [ + "status", + "httpStatus", + "ms", + "firstByteMs", + "responseMs", + "bytes", + "bytesPerSecond", + "attempt", + "rss", + "memoryLimitBytes", + "memoryRatio", + "uptime", + "activeRequests", + "waiting", + "active", + "delayed", + "failed", + "oldestWaitingMs", + "droppedLogs", + "loopP95Ms", + "upstreamStatus", + "stage_repository_ms", + "stage_credential_resolution_ms", + "stage_upstream_ms", + "stage_cache_lookup_ms", + "stage_cache_fill_ms", + "stage_worker_wait_ms", + "stage_anonymize_ms", + "stage_streamer_headers_ms" + ] +} diff --git a/backend/internal/logging/testdata/collector.vrl b/backend/internal/logging/testdata/collector.vrl new file mode 100644 index 0000000..ecaf197 --- /dev/null +++ b/backend/internal/logging/testdata/collector.vrl @@ -0,0 +1,61 @@ +# Rebuild the event from scratch BEFORE the disk buffer. Never retain message, +# Docker metadata, Mongo attr/command, request path, host, UA, cookie or headers. +raw, err = parse_json(string!(.message)) +if err != null { raw = {} } +service = "nginx" +record = raw +if starts_with(string!(.file), "/host/docker/") { + service = string(raw.attrs.tag) ?? "unknown" + if !includes(["api", "streamer", "mongodb", "redis", "mongodb-backup"], service) { abort } + record, err = parse_json(string(raw.log) ?? "") + if err != null { record = {} } +} +out = {"timestamp": now(), "service": service, "severity": "info", "event": "service_output"} +# Use capture time for unsupported formats. Invalid/old producer timestamps +# cannot defeat retention or crash the collector. +event_time = raw.time +if exists(record.time) { event_time = record.time } +if exists(record.timestamp) { event_time = record.timestamp } +parsed, err = parse_timestamp(string(event_time) ?? "", format: "%+") +if err == null { out.timestamp = parsed } +if service == "mongodb" { + out.event = "mongodb_event" + if is_integer(record.id) { out.mongoEventId = record.id } + if includes(["W", "E", "F"], record.s) { out.severity = "warn" } + if includes(["E", "F"], record.s) { out.severity = "error" } +} else if service == "nginx" { + out.event = "edge_request" + record.requestId = record.app_request_id + record.firstByteMs = (to_float(record.upstream_header_time) ?? 0.0) * 1000.0 + record.ms = (to_float(record.request_time) ?? 0.0) * 1000.0 + if is_string(record.edge_request_id) && match(string!(record.edge_request_id), r'^[a-f0-9]{32}$') { out.edge_request_id = record.edge_request_id } + if is_string(record.cf_ray) && match(string!(record.cf_ray), r'^[a-f0-9]{16}-[A-Z]{3}$') { out.cf_ray = record.cf_ray } + if includes(["PASSED", "DELAYED", "REJECTED", "DELAYED_DRY_RUN", "REJECTED_DRY_RUN"], record.limit_req_status) { out.limit_req_status = record.limit_req_status } + # Deliberately omit IPs by default. Original edge JSON has short, restricted + # host retention for incident response; no plain or unsalted hashed IP archive. +} else if includes(["api", "streamer"], service) { + if record.service == "worker" { out.service = "worker" } + if includes(["debug", "info", "warn", "error"], record.severity) { out.severity = record.severity } + if includes(["account_removed", "application_log", "billing_maintenance_failed", "billing_reconciliation_deferred", "billing_requires_attention", "billing_worker_failed", "blob_api_failed_falling_back_to_raw_url", "branch_not_found", "cache_removal_failed", "cache_removed", "checking_repository_status_and_unused_repositories", "cleared_lock_for_active_job", "conference_expire_failed", "content_expiration_failed", "daily_stats_snapshot_failed", "daily_stats_snapshot_stored", "download_completed", "download_start", "downloaded", "downloadfile_failed", "downloading_file", "downloading_gist", "downloading_pull_request", "downloading_via_raw_url_lfs", "duplicate_stripe_customer_requires_review", "ensuretodaysnapshot_failed", "error_log_redis_connect_failed", "expired_repository_cleanup_failed", "failed_removal_recovery_failed", "failed_to_persist_error_status", "failed_to_record_repository_removal_error", "gettoken", "github_primary_rate_limit_hit", "github_secondary_rate_limit_hit", "grant_revocation_failed", "initial_repository_status_check_failed", "job_completed", "job_failed", "job_stalled", "job_started", "lastusedat_update_failed", "login_token_failed", "login_token_req_login_failed", "logout_after_account_removal_failed", "logout_failed", "lookup_failed", "markerrorifinflight_failed", "markerrorifremoving_failed", "metadata_cleanup_complete", "metadata_cleanup_deferred", "owner_access_alert_reset_unavailable", "owner_access_email_accepted", "owner_access_email_audit_unavailable", "owner_access_email_claim_cleanup_unavailable", "owner_access_email_deferred_recovery_unavailable", "owner_access_email_delivery_failed", "owner_access_email_preparation_cleanup_unavailable", "owner_access_email_recovery_recorded", "owner_access_email_recovery_unavailable", "owner_access_email_result_reconciliation_required", "owner_access_email_unavailable", "pr_comments_404_continuing_without_them", "process_fatal_error", "process_heartbeat", "process_started", "progress", "queue_heartbeat", "queued_for_download", "rate_limit_gate_active_delaying_job_before_work", "rate_limit_gate_set", "rate_limited_delaying_job", "recover_failed", "recovered_expired_repository_cleanup", "recovered_file_from_truncated_tree", "recovered_file_invalidation_failed", "recovered_stuck_repo", "recoverstuckpreparing_failed", "recoverstuckremoving_failed", "redis_client_error", "redis_rate_limit_gate_written", "rejected_upstream_download_destination", "removal_failed", "removal_recovery_failed", "removecache_save_failed", "removed_cache_for_unused_repository", "removing_cache", "removing_repository", "repo_claimed", "repository_cache_removal_failed", "repository_expiration_failed", "repository_expired", "repository_removal_failed", "repository_removed", "request_cancelled", "request_completed", "request_slow", "requeued_failed_removal", "requeued_interrupted_removal", "reset", "retired_tree_cleanup_deferred", "retired_tree_cleanup_failed", "running_daily_stats_snapshot", "s3_body_stream_error", "send_failed", "server_started", "source_stream_failed_cache_write_discarded", "staged_tree_cleanup_failed", "staged_tree_completion_deferred", "streamer_fetch_failed", "streamer_started", "streamer_startup_failed", "streamer_zip_fetch_failed", "temporary_storage_cleanup_deferred", "token_refresh_failed_backing_off", "up_to_date", "update_queued", "verify_failed", "waiting_for_rate_limit_gate", "webhook_log", "webhook_processing_failed", "write_failed", "zip_stream_failed"], record.event) { out.event = record.event } + if is_string(record.release) && match(string!(record.release), r'^[a-f0-9]{7,40}$') { out.release = record.release } + if is_string(record.instance) && match(string!(record.instance), r'^[a-f0-9-]{36}$') { out.instance = record.instance } + if includes(["ABORT_ERR", "ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EPIPE", "ETIMEDOUT", "billing_address_missing", "billing_city_missing", "billing_country_missing", "billing_email_missing", "billing_missing", "billing_name_missing", "billing_zip_missing", "branch_not_found", "branch_not_specified", "cache_busy", "cache_miss", "cannot_coauthor_self", "commit_not_specified", "conf_end_date_invalid", "conf_end_date_missing", "conf_id_missing", "conf_id_used", "conf_name_missing", "conf_not_activated", "conf_not_found", "conf_start_date_invalid", "conf_start_date_missing", "conference_not_found", "connection_changed", "download_not_enabled", "expiration_limit_reached", "file_listing_too_large", "file_not_accessible", "file_not_found", "file_not_supported", "file_too_big", "folder_not_supported", "gistId_already_used", "gistId_not_specified", "gist_expired", "gist_not_found", "gist_not_ready", "github_app_access_required", "github_app_reconnect_required", "github_identity_mismatch", "github_rate_limit_exceeded", "github_token_invalid", "github_user_not_found", "invalid_commit_format", "invalid_cursor", "invalid_file_path", "invalid_gistId", "invalid_path", "invalid_plan", "invalid_preserve_files_format", "invalid_project_name", "invalid_pullRequestId", "invalid_repo", "invalid_repoId", "invalid_request", "invalid_settings", "invalid_signature", "invalid_sort", "invalid_status", "invalid_terms_format", "invalid_token_id", "invalid_token_options", "is_removed", "not_authorized", "not_connected", "options_not_provided", "page_not_activated", "page_not_supported_on_different_branch", "path_not_defined", "path_not_specified", "pullRequestId_already_used", "pullRequestId_is_not_a_number", "pullRequestId_not_specified", "pull_request_expired", "pull_request_not_found", "pull_request_not_ready", "token_refresh_failed", "quota_exceeded", "rate_limited", "readme_not_available", "repoId_already_used", "repoId_not_defined", "repoUrl_not_defined", "repo_access_limited", "repo_empty", "repo_not_accessible", "repo_not_found", "repo_saml_enforcement", "repository_archived", "repository_changed", "repository_expired", "repository_job_cancelled", "repository_not_found", "repository_not_ready", "repository_not_specified", "repository_tree_incomplete", "repository_tree_too_large", "s3_config_not_provided", "source_not_provided", "storage_delete_failed", "storage_write_size_mismatch", "submodule_not_available", "terms_not_specified", "token_expired", "token_limit_reached", "unable_to_connect_user", "unable_to_download", "upstream_error", "upstream_timeout", "user_not_found", "username_not_defined", "webhook_processing_failed"], record.errorCode) { out.errorCode = record.errorCode } + if includes(["admin", "anonymized-file", "auth", "billing", "dailyStats", "file-tree", "fs", "gh-stream", "gist", "github", "github-app-webhook", "owner-notifications", "process", "pull-request", "queue", "queue:cache", "queue:download", "queue:remove", "repository", "repository-public", "requests", "route", "route:repo", "s3", "schedule", "server", "streamer", "temporary-storage", "token-auth", "user", "zip-stream"], record.module) { out.module = record.module } + if includes(["protocol", "credentials", "port", "host"], record.reason) { out.reason = record.reason } + if includes(["parse", "find_grant_owners", "reconcile_grant", "persist_installation_block", "reconcile_installation"], record.phase) { out.phase = record.phase } + if includes(["github_app_authorization", "installation", "installation_repositories"], record.webhookEvent) { out.webhookEvent = record.webhookEvent } + if includes(["github.com", "api.github.com", "codeload.github.com", "raw.githubusercontent.com", "media.githubusercontent.com", "other"], record.upstreamHost) { out.upstreamHost = record.upstreamHost } + if includes(["download", "remove", "cache"], record.queue) { out.queue = record.queue } + if includes(["completed", "interrupted"], record.outcome) { out.outcome = record.outcome } +} +for_each(["requestId", "jobId", "deliveryId"]) -> |_index, key| { + value = get(record, [key]) ?? null + if is_string(value) && match(string!(value), r'^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$') { out = set!(out, [key], value) } +} +for_each(["status", "httpStatus", "ms", "firstByteMs", "responseMs", "bytes", "bytesPerSecond", "attempt", "rss", "memoryLimitBytes", "memoryRatio", "uptime", "activeRequests", "waiting", "active", "delayed", "failed", "oldestWaitingMs", "droppedLogs", "loopP95Ms", "upstreamStatus", "stage_repository_ms", "stage_credential_resolution_ms", "stage_upstream_ms", "stage_cache_lookup_ms", "stage_cache_fill_ms", "stage_worker_wait_ms", "stage_anonymize_ms", "stage_streamer_headers_ms"]) -> |_index, key| { + value = get(record, [key]) ?? null + if is_integer(value) || is_float(value) { out = set!(out, [key], value) } +} +if includes(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "OTHER"], record.method) { out.method = record.method } +if includes(["/", "other", "/dashboard", "/anonymize", "/healthcheck", "/api/healthcheck", "/api", "/api/download", "/api/stat", "/api/stat/history", "/api/options", "/api/message", "/api/user", "/api/user/quota", "/api/user/dashboard", "/api/repo", "/api/anonymize-preview", "/api/admin/overview", "/api/admin/performance", "/api/admin/errors", "/api/admin/errors/stats", "/api/admin/queues", "/api/admin/queues/metrics", "/github/app/webhook", "/api/repo/:repoId", "/api/repo/:repoId/file/:path", "/api/repo/:repoId/files", "/api/repo/:repoId/files/counts", "/api/repo/:repoId/files/search", "/api/repo/:repoId/zip", "/api/repo/:repoId/options", "/api/repo/:repoId/refresh", "/api/repo/:repoId/coauthors", "/api/repo/:repoId/extend", "/api/repo/:owner/:repo/readme", "/api/repo/:owner/:repo/branches", "/w/:repoId/:path", "/r/:repoId/:path", "/api/pr/:id/:path", "/api/gist/:id/:path", "/assets/:path", "/github/:action", "/api/admin/:action", "/api/user/:action", "/api/repo/:id/file/:path", "/api/repo/:id/files/counts", "/api/repo/:id/files/search", "/api/repo/:id/files", "/api/repo/:id/zip", "/api/repo/:id", "/viewer/:id/:path"], record.route) { out.route = record.route } +. = out diff --git a/backend/internal/server/discovery_integration_test.go b/backend/internal/server/discovery_integration_test.go index f4b0f19..ff593bd 100644 --- a/backend/internal/server/discovery_integration_test.go +++ b/backend/internal/server/discovery_integration_test.go @@ -23,15 +23,19 @@ func runDiscoveryIntegration(t *testing.T, base *Server) { failure string want []string wantError bool + status int }{ - {"OAuth only", true, false, "", []string{"legacy/one", "legacy/two"}, false}, - {"App only", false, true, "", []string{"app/two", "app/three"}, false}, - {"combined order and replacement", true, true, "", []string{"legacy/one", "app/two", "app/three"}, false}, - {"installation failure fallback", true, true, "/user/installations", []string{"legacy/one", "legacy/two"}, false}, - {"repository failure fallback", true, true, "/user/installations/1/repositories", []string{"legacy/one", "legacy/two"}, false}, - {"discard partial App results", true, true, "/user/installations/2/repositories", []string{"legacy/one", "legacy/two"}, false}, - {"App failure without OAuth", false, true, "/user/installations/2/repositories", nil, true}, - {"OAuth failure remains fatal", true, true, "/user/repos", nil, true}, + {"OAuth only", true, false, "", []string{"legacy/one", "legacy/two"}, false, 0}, + {"App only", false, true, "", []string{"app/two", "app/three"}, false, 0}, + {"combined order and replacement", true, true, "", []string{"legacy/one", "app/two", "app/three"}, false, 0}, + {"installation failure fallback", true, true, "/user/installations", []string{"legacy/one", "legacy/two"}, false, 0}, + {"repository failure fallback", true, true, "/user/installations/1/repositories", []string{"legacy/one", "legacy/two"}, false, 0}, + {"discard partial App results", true, true, "/user/installations/2/repositories", []string{"legacy/one", "legacy/two"}, false, 0}, + {"App failure without OAuth", false, true, "/user/installations/2/repositories", nil, true, 0}, + {"OAuth failure remains fatal", true, true, "/user/repos", nil, true, 0}, + {"OAuth credential denied", true, false, "/user/repos", nil, true, 401}, + {"OAuth permission denied", true, false, "/user/repos", nil, true, 403}, + {"App credential denied", false, true, "/user/installations", nil, true, 401}, } { t.Run(c.name, func(t *testing.T) { ctx := context.Background() @@ -78,6 +82,9 @@ func runDiscoveryIntegration(t *testing.T, base *Server) { var body any if path == c.failure { status = 500 + if c.status != 0 { + status = c.status + } body = M{"message": "synthetic private upstream detail"} } else { switch path { @@ -111,6 +118,15 @@ func runDiscoveryIntegration(t *testing.T, base *Server) { if !errors.As(err, &api) || strings.Contains(err.Error(), "private upstream") { t.Fatalf("unexpected discovery error: %v", err) } + if c.status == 401 && c.oauth && (api.Code != "token_expired" || api.Status != 401) { + t.Fatal("OAuth denial misclassified", api) + } + if c.status == 401 && !c.oauth && api.Code != "github_app_reconnect_required" { + t.Fatal("App denial misclassified", api) + } + if c.status == 403 && api.Code == "token_expired" { + t.Fatal("Permission denial treated as expired token") + } if len(repos) != 0 { t.Fatal("returned partial discovery on failure") } diff --git a/backend/internal/server/error_log.go b/backend/internal/server/error_log.go index cb90532..faadd74 100644 --- a/backend/internal/server/error_log.go +++ b/backend/internal/server/error_log.go @@ -82,6 +82,9 @@ func (s *Server) enqueueError(level, module, message, code string, status int, d if !slog.Default().Enabled(context.Background(), severity) { return } + if module != "requests" { + slog.Log(context.Background(), severity, message, "module", module, "code", code, "httpStatus", status, "requestId", str(detail["requestId"])) + } at := time.Now().UTC() bucket := errorBucket(status, level) data, err := json.Marshal(M{"ts": at, "module": module, "level": level, "message": message, "raw": []any{message, detail}}) diff --git a/backend/internal/server/integration_test.go b/backend/internal/server/integration_test.go index c25d76d..ea75619 100644 --- a/backend/internal/server/integration_test.go +++ b/backend/internal/server/integration_test.go @@ -131,6 +131,7 @@ func TestBackendIntegration(t *testing.T) { } t.Run("owner notification lifecycle", func(t *testing.T) { runOwnerAlertsIntegration(t, server) }) t.Run("email delivery history", func(t *testing.T) { runEmailHistoryIntegration(t, server) }) + t.Run("job structured logging", func(t *testing.T) { runJobLoggingIntegration(t, server) }) t.Run("hosting quota jobs", func(t *testing.T) { runQuotaJobIntegration(t, server) }) t.Run("billing lifecycle", func(t *testing.T) { runBillingIntegration(t, server) }) t.Run("second provider lifecycle", func(t *testing.T) { runProviderIntegration(t, server, fakeProvider, call, token, otherToken) }) diff --git a/backend/internal/server/job_logging_integration_test.go b/backend/internal/server/job_logging_integration_test.go new file mode 100644 index 0000000..cbbe54a --- /dev/null +++ b/backend/internal/server/job_logging_integration_test.go @@ -0,0 +1,73 @@ +package server + +import ( + "context" + "encoding/json" + "log/slog" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/tdurieux/anonymous_github/backend/internal/logging" + "go.mongodb.org/mongo-driver/v2/bson" +) + +type jobLogWriter struct { + rows []M + cancel context.CancelFunc + t *testing.T +} + +func (w *jobLogWriter) Write(data []byte) (int, error) { + row := M{} + if err := json.Unmarshal(data, &row); err != nil { + w.t.Error(err) + } + if strings.Contains(string(data), "private-resource") { + w.t.Error("resource identifier leaked") + } + w.rows = append(w.rows, row) + if row["event"] == "job_completed" { + w.cancel() + } + return len(data), nil +} + +func runJobLoggingIntegration(t *testing.T, base *Server) { + ctx := t.Context() + db := base.Store.DB.Client().Database("job_logging_test_" + bson.NewObjectID().Hex()) + defer db.Drop(ctx) + s := &Server{Store: &Store{DB: db, Redis: base.Store.Redis}} + trace := newRequestTrace() + requestCtx := context.WithValue(ctx, performanceContextKey{}, trace) + if err := s.enqueue(requestCtx, "repo", "private-resource", "prepare"); err != nil { + t.Fatal(err) + } + prior := slog.Default() + defer slog.SetDefault(prior) + var firstID string + for attempt := int64(1); attempt <= 2; attempt++ { + work, cancel := context.WithTimeout(ctx, 5*time.Second) + output := &jobLogWriter{cancel: cancel, t: t} + slog.SetDefault(slog.New(logging.New(output, slog.LevelInfo, ""))) + s.jobLoop(work, "download") + cancel() + if len(output.rows) != 2 || output.rows[0]["event"] != "job_started" || output.rows[1]["event"] != "job_completed" { + t.Fatal(output.rows) + } + row := output.rows[1] + id := str(row["jobId"]) + if _, err := uuid.Parse(id); err != nil || number(row["attempt"]) != attempt || row["requestId"] != trace.id { + t.Fatal(row) + } + if attempt == 1 { + firstID = id + } else if firstID != id { + t.Fatal("retry lost trace", firstID, id) + } + if _, err := s.Store.update(ctx, "gojobs", M{"_id": "repo:private-resource:prepare"}, M{"$set": M{"state": "waiting", "availableAt": time.Now()}}); err != nil { + t.Fatal(err) + } + } +} diff --git a/backend/internal/server/jobs.go b/backend/internal/server/jobs.go index 31d4d63..c34f8b0 100644 --- a/backend/internal/server/jobs.go +++ b/backend/internal/server/jobs.go @@ -3,11 +3,13 @@ package server import ( "context" "errors" + "github.com/google/uuid" "github.com/tdurieux/anonymous_github/backend/internal/provider" "github.com/tdurieux/anonymous_github/backend/internal/security" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" + "log/slog" "path" "strconv" "strings" @@ -29,7 +31,11 @@ func (s *Server) enqueue(ctx context.Context, kind, id, action string) error { return err } key := kind + ":" + id + ":" + action - _, err = s.Store.DB.Collection("gojobs").UpdateOne(ctx, M{"_id": key, "state": M{"$nin": []string{"active", "waiting", "delayed"}}}, M{"$set": M{"kind": kind, "resourceId": id, "action": action, "state": "waiting", "attempts": 0, "priority": 0, "availableAt": time.Now(), "createdAt": time.Now()}}, options.UpdateOne().SetUpsert(true)) + requestID := "" + if trace := traceFrom(ctx); trace != nil { + requestID = trace.id + } + _, err = s.Store.DB.Collection("gojobs").UpdateOne(ctx, M{"_id": key, "state": M{"$nin": []string{"active", "waiting", "delayed"}}}, M{"$set": M{"kind": kind, "resourceId": id, "action": action, "logJobId": uuid.NewString(), "requestId": requestID, "state": "waiting", "attempts": 0, "priority": 0, "availableAt": time.Now(), "createdAt": time.Now()}}, options.UpdateOne().SetUpsert(true)) if mongo.IsDuplicateKeyError(err) { return nil } @@ -112,12 +118,31 @@ func (s *Server) jobLoop(ctx context.Context, queue string) { } work, cancel := context.WithTimeout(ctx, 90*time.Second) jobStarted := time.Now() + jobID := str(job["logJobId"]) + if parsed, parseErr := uuid.Parse(jobID); parseErr != nil || parsed.String() != jobID { + jobID = uuid.NewString() + s.Store.update(ctx, "gojobs", M{"_id": job["_id"], "lease": token}, M{"$set": M{"logJobId": jobID}}) + } + logger := slog.Default().With("jobId", jobID, "requestId", str(job["requestId"]), "service", "worker", "module", "queue", "queue", queue, "attempt", number(job["attempts"])) + logger.InfoContext(work, "job started") err = s.runJob(work, job) if _, delayed := jobRateLimit(job, err, time.Now()); !delayed { s.queueMetric(ctx, job, err != nil, time.Since(jobStarted)) } cancel() - s.finishJob(ctx, job, err, time.Now()) + finishErr := s.finishJob(ctx, job, err, time.Now()) + if finishErr != nil { + logger.ErrorContext(ctx, "job failed", "ms", float64(time.Since(jobStarted))/float64(time.Millisecond)) + } else if err != nil { + code := "upstream_error" + var api *APIError + if errors.As(providerFailure(err), &api) { + code = api.Code + } + logger.WarnContext(ctx, "job failed", "code", code, "ms", float64(time.Since(jobStarted))/float64(time.Millisecond)) + } else { + logger.InfoContext(ctx, "job completed", "ms", float64(time.Since(jobStarted))/float64(time.Millisecond)) + } } } func (s *Server) runJob(ctx context.Context, job M) (jobErr error) { diff --git a/backend/internal/server/logging_test.go b/backend/internal/server/logging_test.go new file mode 100644 index 0000000..e193195 --- /dev/null +++ b/backend/internal/server/logging_test.go @@ -0,0 +1,46 @@ +package server + +import ( + "bytes" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "log/slog" + "net/http/httptest" + "strings" + "testing" + + "github.com/tdurieux/anonymous_github/backend/internal/logging" +) + +func TestWebhookFailureStructuredDiagnostics(t *testing.T) { + var output bytes.Buffer + previous := slog.Default() + slog.SetDefault(slog.New(logging.New(&output, slog.LevelInfo, ""))) + defer slog.SetDefault(previous) + s := &Server{Config: Config{AppEnabled: true, AppWebhookSecret: "synthetic-key"}} + payload := `{"secret-repository":` + mac := hmac.New(sha256.New, []byte(s.Config.AppWebhookSecret)) + mac.Write([]byte(payload)) + r := httptest.NewRequest("POST", "/github/app/webhook?secret-query", strings.NewReader(payload)) + r.Header.Set("Content-Type", "application/json") + r.Header.Set("X-Hub-Signature-256", "sha256="+hex.EncodeToString(mac.Sum(nil))) + r.Header.Set("X-GitHub-Event", "installation") + r.Header.Set("X-GitHub-Delivery", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa") + w := httptest.NewRecorder() + s.webhook(w, r) + if w.Code != 503 { + t.Fatal(w.Code, w.Body.String()) + } + var record M + if err := json.Unmarshal(output.Bytes(), &record); err != nil { + t.Fatal(err, output.String()) + } + if record["event"] != "webhook_processing_failed" || record["phase"] != "parse" || record["webhookEvent"] != "installation" || record["deliveryId"] == nil { + t.Fatal(record) + } + if strings.Contains(output.String(), "secret") || strings.Contains(output.String(), "synthetic") { + t.Fatal(output.String()) + } +} diff --git a/backend/internal/server/process_metrics.go b/backend/internal/server/process_metrics.go index 880830e..d268070 100644 --- a/backend/internal/server/process_metrics.go +++ b/backend/internal/server/process_metrics.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "io" + "log/slog" "os" "runtime" "strconv" @@ -65,6 +66,11 @@ func (s *Server) processSample(now time.Time) M { if !m.lastFlush.IsZero() { sample["lastFlushAt"] = m.lastFlush.UnixMilli() } + fields := []any{"module", "process", "rss", system["processRss"], "memoryLimitBytes", sample["memoryLimitBytes"], "uptime", uptime, "activeRequests", m.active.Load()} + if limit := number(sample["memoryLimitBytes"]); limit > 0 { + fields = append(fields, "memoryRatio", float64(number(system["processRss"]))/float64(limit)) + } + slog.Info("process heartbeat", fields...) m.sampledAt = now return sample } diff --git a/backend/internal/server/provider_github_discovery.go b/backend/internal/server/provider_github_discovery.go index 1bf87b5..041a3a3 100644 --- a/backend/internal/server/provider_github_discovery.go +++ b/backend/internal/server/provider_github_discovery.go @@ -2,6 +2,7 @@ package server import ( "context" + "errors" "fmt" "github.com/tdurieux/anonymous_github/backend/internal/provider" ) @@ -66,6 +67,10 @@ func (g *githubProvider) List(ctx context.Context, request provider.ListRequest) } err := s.githubPages(ctx, endpoint, oauthToken, "", func(r M) bool { remember(r); return false }) if err != nil { + var upstream *githubHTTPError + if errors.As(err, &upstream) && upstream.status == 401 { + return nil, fail("token_expired", 401) + } return nil, err } } diff --git a/backend/internal/server/request_trace.go b/backend/internal/server/request_trace.go index 6f64156..a2002f6 100644 --- a/backend/internal/server/request_trace.go +++ b/backend/internal/server/request_trace.go @@ -53,7 +53,7 @@ func (t *requestTrace) log(r *http.Request, state *responseState, route, method if aborted { outcome = "interrupted" } - fields := []any{"requestId", t.id, "service", "api", "method", method, "route", route, "status", status, "outcome", outcome, "ms", math.Round(float64(elapsed) / float64(time.Millisecond)), "firstByteMs", firstByte, "bytes", bytes, "stages", stages} + fields := []any{"requestId", t.id, "service", "api", "module", "requests", "method", method, "route", route, "status", status, "outcome", outcome, "ms", math.Round(float64(elapsed) / float64(time.Millisecond)), "firstByteMs", firstByte, "bytes", bytes, "stages", stages} switch { case aborted: t.logger.WarnContext(r.Context(), "request interrupted", fields...) diff --git a/backend/internal/server/webhook.go b/backend/internal/server/webhook.go index 0b2d0e1..4238394 100644 --- a/backend/internal/server/webhook.go +++ b/backend/internal/server/webhook.go @@ -7,6 +7,7 @@ import ( "fmt" "github.com/tdurieux/anonymous_github/backend/internal/security" "go.mongodb.org/mongo-driver/v2/mongo/options" + "log/slog" "mime" "net/http" "time" @@ -41,53 +42,70 @@ func (s *Server) webhook(w http.ResponseWriter, r *http.Request) { writeError(w, fail("invalid_webhook_signature", 401)) return } - var decoded any - if json.Unmarshal(body, &decoded) != nil { + eventName := r.Header.Get("X-GitHub-Event") + phase := "parse" + failed := func(cause error) { + fields := []any{"module", "github-app-webhook", "phase", phase, "webhookEvent", eventName, "deliveryId", r.Header.Get("X-GitHub-Delivery")} + if trace := traceFrom(r.Context()); trace != nil { + fields = append(fields, "requestId", trace.id) + } + var api *APIError + if errors.As(providerFailure(cause), &api) && api.Status >= 400 && api.Status <= 599 { + fields = append(fields, "upstreamStatus", api.Status) + } + slog.ErrorContext(r.Context(), "webhook processing failed", fields...) writeError(w, fail("webhook_processing_failed", 503)) + } + var decoded any + if err = json.Unmarshal(body, &decoded); err != nil { + failed(err) return } - eventName := r.Header.Get("X-GitHub-Event") if decoded == nil && (eventName == "installation" || eventName == "installation_repositories" || eventName == "github_app_authorization") { - writeError(w, fail("webhook_processing_failed", 503)) + failed(err) return } event := obj(decoded) installation := obj(event["installation"]) if (eventName == "installation" || eventName == "installation_repositories") && jsonSafeInteger(installation["id"]) && str(installation["app_id"]) == s.Config.AppID { + phase = "persist_installation_block" revision, err := security.RandomToken() if err != nil { - writeError(w, fail("webhook_processing_failed", 503)) + failed(err) return } filter := M{"appId": s.Config.AppID, "installationId": installation["id"]} _, err = s.Store.DB.Collection("githubinstallations").UpdateOne(r.Context(), filter, M{"$set": M{"blocked": true, "revision": revision, "reconciliationPending": str(event["action"]) != "deleted"}}, options.UpdateOne().SetUpsert(true)) if err != nil { - writeError(w, fail("webhook_processing_failed", 503)) + failed(err) return } if str(event["action"]) != "deleted" { + phase = "reconcile_installation" jwt, err := s.appJWT() if err != nil { - writeError(w, fail("webhook_processing_failed", 503)) + failed(err) return } err = s.reconcileInstallation(r.Context(), number(installation["id"]), revision, jwt) if err != nil { - writeError(w, fail("webhook_processing_failed", 503)) + failed(err) return } } } if eventName == "github_app_authorization" && str(event["action"]) == "revoked" && inputTruthy(obj(event["sender"])["id"]) { + phase = "find_grant_owners" users, err := s.Store.list(r.Context(), "users", M{"externalIDs.github": str(obj(event["sender"])["id"])}, 0, nil) if err != nil { - writeError(w, fail("webhook_processing_failed", 503)) + failed(err) return } + phase = "reconcile_grant" for _, u := range users { row, err := s.Store.one(r.Context(), "credentials", M{"ownerId": u["_id"], "provider": "github-app-user"}) if err != nil { - writeError(w, fail("webhook_processing_failed", 503)) + failed(err) return } if row == nil || boolean(row["revoked"]) { @@ -95,12 +113,12 @@ func (s *Server) webhook(w http.ResponseWriter, r *http.Request) { } ok, err := s.Store.update(r.Context(), "credentials", M{"_id": row["_id"], "revision": row["revision"]}, M{"$set": M{"reconciliationPending": true}}) if err != nil { - writeError(w, fail("webhook_processing_failed", 503)) + failed(err) return } if ok { if err = s.reconcileGrant(r.Context(), row); err != nil { - writeError(w, fail("webhook_processing_failed", 503)) + failed(err) return } } diff --git a/backend/reports/main-alignment.json b/backend/reports/main-alignment.json index d05554a..dcbdd28 100644 --- a/backend/reports/main-alignment.json +++ b/backend/reports/main-alignment.json @@ -21,7 +21,9 @@ "openPRFocusedNodeTests": "42 email-history, expiration and admin UI tests passed; final 25-test activity/error-code/preview regression set passed", "frontendBuild": "passed with regenerated asset manifest and bundles", "nodeSuite": "Broad run: 1676 passed, 436 skipped, five failures. Fixed missing cache_miss translation, three stale Mongoose query mocks and one stale preview-button selector; all five failures passed in a 25-test focused rerun. Full suite not repeated after these fixes.", - "typescript": "tsc --noEmit passed" + "typescript": "tsc --noEmit passed", + "structuredLogging": "Passed race tests for private-data filtering, concurrent output, request traces, process samples, webhook failure diagnostics and persistent job traces. Actual Go records passed the unmodified Vector 0.61.0 sanitizer using the PR-pinned image digest. Final focused regression run and go vet passed.", + "oauthDiscoveryDenial": "Disposable database race test passed for OAuth/App discovery, OAuth 401, permission 403 and App reconnect semantics." }, "changes": [ "Restore Go backend and Go deployment on top of current main", @@ -41,7 +43,9 @@ "Stop automatic hosting-quota retries, preserve HTTP 402, and retain explicit owner recovery", "Preserve Node HTTP status mappings for stored repository failures", "Recognize named Express Router imports in route inventory generation", - "Repair current Node activity-test query mocks and preview-button selector; add the missing cache_miss translation" + "Repair current Node activity-test query mocks and preview-button selector; add the missing cache_miss translation", + "Emit safe structured JSON logs, persist job/request trace correlation, add process memory heartbeats and webhook failure phases", + "Normalize confirmed legacy OAuth discovery credential denial without changing App reconnect errors" ], "implementedTypeScriptRoutes": [ { @@ -123,11 +127,11 @@ }, "955": { "head": "b456ab8739374bf8bb3a690ad55698fb61615dd1", - "result": "Go hosting-quota retry and stored-error status fixes implemented. Broader diagnostic parity remains to review." + "result": "Quota retries/status mapping fixed; webhook failure phases and structured error severity implemented. Legacy OAuth discovery 401 maps to token_expired while App and permission errors remain distinct. Go direct-folder queries already use equality." }, "956": { "head": "f084f5cbfc7b328a04b4e7e859ce9fa224c605c4", - "result": "Stacked on #955. Go text logs are incompatible with the new JSON collector schema; structured logging adaptation remains outstanding." + "result": "Go JSON logging implemented and tested against its pinned, unmodified Vector sanitizer. Request timings, job traces, errors and memory heartbeats retained. Aggregate queue-heartbeat output and deployment of the logging stack remain outstanding; fixed Go ZIP stage/reason fields remain local only." }, "checks": "GitHub Actions jobs did not start because the account is locked due to a billing issue. This is not a test failure." }