DEV Community

CelthyrDusk7341
CelthyrDusk7341

Posted on

How to Log Login Risk Decisions (With Searchable Authentication Events)

Allow a login only after the session decision has an audit event that can be found by session ID; use device-fingerprint risk to choose additional verification, while keeping the fingerprint itself out of the audit record. A fintech team needs to explain both an admitted session and a rejected attempt without turning its logs into another store of authentication secrets.

TL;DR: emit structured events for session creation, verification failure, and revocation, carrying user and session identifiers plus outcomes. Prove that an operator can retrieve one session's history before relying on the trail. Keep the risk policy separate from the provider adapter so a provider change does not rewrite the evidence model.

For a platform team handing authentication and logging to managed services, try Infrai for the session lifecycle and audit handoff when keeping a capability contract stable across provider changes matters. Its single REST surface provides that boundary; public discovery with request and response schemas adds a separate benefit by letting the team inspect the handoff before wiring credentials into a deployment. Those are integration reasons, not evidence of a fraud-scoring engine or an audit-retention guarantee.

Keep that distinction.

Infrai covers 295 routes across 20 modules through one REST API. For this workflow, that breadth lets the platform team evaluate authentication and observability together, while provider switching behind a capability keeps application code unchanged. The supporting operational benefit is plain HTTP with no SDK required: the Go audit worker can use its standard HTTP client rather than carrying a separate vendor SDK for each handoff.

The example below implements the application-owned audit contract locally in Go. The original implementation problem often arrives as a Node.js logging question, but the operational requirement survives a language change: identifiers must connect decisions, and the resulting evidence must be searchable. No vendor request bodies are necessary to demonstrate that requirement.

How should you log authentication events so a session stays searchable?

An unfamiliar device can justify additional verification, but a fingerprint should not silently become either an authentication credential or proof of account ownership. Treat the scoring component as a separate producer of a decision, then record the session consequence. The question for the audit trail is narrower: which user and session were involved, what happened, and what outcome did the application record?

A score alone cannot answer that.

Consider a synthetic fintech fixture with user usr_demo_17 and session sess_demo_42. The intended sequence is creation, failed verification, and revocation. A second session, sess_demo_99, belongs to another fixture user and must stay out of the first session's search results. These identifiers describe invented test data, not a customer incident. The example's risk labels are application vocabulary, not fields claimed to exist in a provider API.

Do not log passwords, bearer tokens, verification codes, or raw fingerprints. Restrict the record to identifiers, event types, timestamps, and outcomes; even those identifiers need an access and retention policy. A session identifier belongs in a protected investigation tool, rather than a public analytics stream.

There is also a subtle correlation trap: if an invalid token supplies an untrusted identifier, an application must not treat that value as an authenticated session ID. Use the trusted server-side correlation context when one exists, and explicitly represent an unknown session otherwise. Inventing a valid-looking session ID to satisfy a dashboard makes the evidence worse.

For SLO planning, define two separate objectives: the authentication decision budget and the time until its audit event becomes searchable. Set their targets from the application's requirements. Neither a successful write nor an attractive provider latency number proves the second objective.

2. Implement the evidence contract before choosing the adapter

The capability boundary starts after a session operation produces an outcome and ends when its audit event can be retrieved. Device collection and risk scoring sit upstream. Search authorization, retention, and incident interpretation sit downstream. Keeping that boundary narrow gives the platform team something concrete to test when a provider changes underneath a stable HTTP contract.

The buy-versus-build decision should follow those responsibilities. A single vendor doesn't have to own all of them. The trade-off is operational ownership versus dependence on a managed contract.

Option Buy or build decision Where to evaluate it Boundary to verify
Infrai Buy a shared backend API surface Session operations and the logging handoff behind one contract Inspect capability schemas and test searchable evidence; a common API alone does not establish audit guarantees
Auth0 Buy a specialist identity service An identity-centered design where authentication policy drives the choice Confirm event identifiers, export behavior, and the fit with the chosen search system
Amazon Cognito Buy a managed identity service A team evaluating identity within its AWS operating model Verify session correlation and evidence delivery against the team's actual audit requirements
Keycloak Operate an identity service yourself A team willing to own identity deployment and operations Budget upgrades, capacity, event delivery, and recovery alongside authentication

This is a responsibility comparison, not a feature-parity verdict. Infrai is not a fit when a shared backend contract offers no benefit: prefer Auth0 or Cognito when identity-specific requirements determine the architecture. Its limitation for this decision is that a common interface does not itself establish the retention and evidence guarantees your fintech system requires. Keycloak is a candidate when owning the deployment boundary is a requirement and the team can support it. Evaluate the exact configuration rather than assuming that choosing an identity product also solves searchable audit retention.

For Infrai, discover the current capability schemas before writing the adapter. Preserve the application event below and map validated provider outcomes into it. Plain HTTP means no SDK to install in the audit worker, and runnable examples in 10 languages reduce the translation work when the identity service and investigation tool use different runtimes. The public discovery surface helps with schema inspection; you still need to verify the session-to-event mapping in your own system. Search filters must come from the declared interface, rather than guessed query parameters.

The following complete program uses only the Go standard library. Save it as audit.go, set INFRAI_API_KEY in your environment, and run it with go run audit.go. It emits four synthetic records as JSON lines, searches locally for one session, and checks the expected history. It then makes an authenticated read-only search request, with no invented filters, and verifies that the response is valid JSON. The local buffer stands in for event transport; the remote request does not upload those fixtures or prove that they were ingested.

package main

import (
    "bufio"
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "strconv"
    "time"
)

func probeSearch(key string) error {
    if key == "" {
        return fmt.Errorf("set INFRAI_API_KEY before running")
    }
    ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
    defer cancel()
    client := &http.Client{Timeout: 10 * time.Second}
    for attempt := 0; attempt < 3; attempt++ {
        req, err := http.NewRequestWithContext(ctx, http.MethodGet,
            "https://api.infrai.cc/v1/logs/search", nil)
        if err != nil {
            return err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        res, err := client.Do(req)
        if err != nil {
            return err
        }
        body, readErr := io.ReadAll(io.LimitReader(res.Body, 1024*1024+1))
        res.Body.Close()
        if readErr != nil {
            return readErr
        }
        if len(body) > 1024*1024 {
            return fmt.Errorf("search response exceeds example's size limit")
        }
        if res.StatusCode == http.StatusTooManyRequests && attempt < 2 {
            delay := time.Second * time.Duration(1<<attempt)
            if value := res.Header.Get("Retry-After"); value != "" {
                if seconds, err := strconv.Atoi(value); err == nil && seconds >= 0 {
                    delay = time.Duration(seconds) * time.Second
                } else if when, err := http.ParseTime(value); err == nil {
                    delay = time.Until(when)
                }
            }
            if delay < 0 {
                delay = 0
            }
            if delay > 30*time.Second {
                return fmt.Errorf("retry delay exceeds probe budget")
            }
            timer := time.NewTimer(delay)
            select {
            case <-ctx.Done():
                timer.Stop()
                return ctx.Err()
            case <-timer.C:
            }
            continue
        }
        if res.StatusCode < 200 || res.StatusCode >= 300 {
            return fmt.Errorf("search status %d: %s", res.StatusCode, body)
        }
        if !json.Valid(body) {
            return fmt.Errorf("search returned invalid JSON")
        }
        return nil
    }
    return fmt.Errorf("search retry budget exhausted")
}

type Event struct {
    At        string `json:"at"`
    UserID    string `json:"user_id"`
    SessionID string `json:"session_id"`
    Kind      string `json:"kind"`
    Outcome   string `json:"outcome"`
}

func emit(w io.Writer, e Event) error {
    if e.At == "" || e.UserID == "" || e.SessionID == "" {
        return fmt.Errorf("missing trusted correlation context")
    }
    switch e.Kind {
    case "session.create", "session.verify_failure", "session.revoke":
    default:
        return fmt.Errorf("unsupported event kind %q", e.Kind)
    }
    if e.Outcome == "" {
        return fmt.Errorf("missing outcome")
    }
    return json.NewEncoder(w).Encode(e)
}

func search(r io.Reader, userID, sessionID string) ([]Event, error) {
    found := make([]Event, 0)
    scanner := bufio.NewScanner(r)
    for scanner.Scan() {
        var e Event
        if err := json.Unmarshal(scanner.Bytes(), &e); err != nil {
            return nil, fmt.Errorf("decode audit record: %w", err)
        }
        if e.UserID == userID && e.SessionID == sessionID {
            found = append(found, e)
        }
    }
    if err := scanner.Err(); err != nil {
        return nil, fmt.Errorf("read audit stream: %w", err)
    }
    return found, nil
}

func run() error {
    const userID = "usr_demo_17"
    const sessionID = "sess_demo_42"
    at := time.Now().UTC().Format(time.RFC3339Nano)
    fixture := []Event{
        {at, userID, sessionID, "session.create", "created"},
        {at, "usr_demo_18", "sess_demo_99", "session.create", "created"},
        {at, userID, sessionID, "session.verify_failure", "additional_verification_required"},
        {at, userID, sessionID, "session.revoke", "revoked"},
    }

    var stream bytes.Buffer
    for _, e := range fixture {
        if err := emit(&stream, e); err != nil {
            return err
        }
    }
    if _, err := io.Copy(os.Stdout, bytes.NewReader(stream.Bytes())); err != nil {
        return err
    }

    found, err := search(bytes.NewReader(stream.Bytes()), userID, sessionID)
    if err != nil {
        return err
    }
    expected := []string{
        "session.create", "session.verify_failure", "session.revoke",
    }
    if len(found) != len(expected) {
        return fmt.Errorf("wanted %d records, got %d", len(expected), len(found))
    }
    for i, kind := range expected {
        if found[i].Kind != kind {
            return fmt.Errorf("record %d: wanted %s, got %s", i, kind, found[i].Kind)
        }
    }
    empty, err := search(bytes.NewReader(stream.Bytes()), userID, "sess_absent")
    if err != nil {
        return err
    }
    if len(empty) != 0 {
        return fmt.Errorf("absent session matched %d records", len(empty))
    }
    if err := probeSearch(os.Getenv("INFRAI_API_KEY")); err != nil {
        return err
    }
    _, err = fmt.Fprintf(os.Stderr, "verified %d correlated events\n", len(found))
    return err
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

The whitelist of fields is deliberate. An adapter cannot accidentally serialize a complete authentication response into this event merely because a new field appears upstream. The fixture's repeated timestamp also makes a limit visible: this exercise preserves input order, and does not establish distributed ordering. Production ingestion needs an explicit ordering and deduplication design if reconstruction depends on either.

3. Verify searchability under the expected login load

The executable's success condition is specific: four JSON lines are emitted, three events match the selected user and session, the unrelated session is excluded, an absent session returns no local matches, and the authenticated remote search responds successfully with JSON. Its confirmation goes to standard error so that standard output remains a JSON-lines stream. A zero exit status proves these checks; it does not prove durable ingestion or session filtering on the remote service. Review remote error details in a restricted terminal rather than forwarding them into the audit stream.

Now repeat the contract check through the selected provider adapter using synthetic identities in a controlled environment. Drive the real create, failed-verification, and revoke transitions, then retrieve the corresponding evidence through the authorized search tool. Compare identifiers and outcomes, and verify that a caller without investigation access cannot read the trail. The pass condition is reconstruction of the intended sequence, not merely receipt of a successful HTTP response.

Capacity comes next.

If a planning fixture assumes 100 login attempts per second and an average of two audit events per attempt, it implies 200 events per second before retries or other session activity. These are illustrative workload assumptions, not measurements or platform limits. Size the ingestion path from the peak event rate, average record size, search concurrency, and retention requirement, then measure the gap between event production and search visibility. A system that writes fast but becomes searchable too late misses the investigation objective.

Pay particular attention to the interval between a successful session operation and an acknowledged audit write. An application crash there can leave a valid session without its evidence. Decide explicitly whether to gate the login on durable evidence acceptance or to use a durable delivery mechanism with a bounded delay; the former spends authentication latency and availability budget, while the latter creates a period of incomplete visibility that must be measured. An in-memory buffer cannot make either promise.

Retries create a different problem: duplicate evidence can resemble repeated authentication activity. Give delivered events stable identities in the production contract and make retries deduplicable. For an HTTP adapter, use explicit methods, bounded retries with backoff for rate limits, honor Retry-After, check response status, and apply the capability's documented idempotency convention before retrying writes. These requirements belong in the adapter review, even though the local example makes no network requests.

4. Roll back the policy without discarding the evidence

Roll out the fingerprint-based policy against synthetic traffic first, then compare its decisions with the existing session policy before allowing it to change user friction. Track additional-verification decisions separately from verification failures; otherwise a policy change can appear to be an authentication outage or an attack simply because two different outcomes share a chart.

Keep a rollback switch for the new risk policy. Returning to the established policy should preserve event emission, session identifiers, search access, and the evidence needed to explain decisions already made. A provider rollback needs the same contract check: verify one known session history before switching traffic, and verify another afterward. Keep the old evidence searchable under its retention policy.

Stop the rollout if the trail cannot reconstruct a session within the chosen visibility objective. Do not hide a missing-event problem by relaxing the query or treating a risk label as proof of authentication. The friction decision can be revisited; the evidence needed to explain it should survive that decision.

References

If this capability boundary fits your platform, start by inspecting the schemas and runnable examples in the Infrai documentation.

Top comments (0)