diff --git a/ipn/auditlog/auditlog.go b/ipn/auditlog/auditlog.go index 0d6bd278d..4d715fafd 100644 --- a/ipn/auditlog/auditlog.go +++ b/ipn/auditlog/auditlog.go @@ -162,9 +162,14 @@ func (al *Logger) Start(t Transport) error { } al.transport = t - pending, err := al.storedCountLocked() - if err != nil { - al.logf("[unexpected] failed to restore logs: %v", err) + var pending int + // A profile that has not been persisted yet has no ID, + // and no stored logs to restore. + if al.profileID != "" { + var err error + if pending, err = al.storedCountLocked(); err != nil { + al.logf("[unexpected] failed to restore logs: %v", err) + } } go al.flushWorker() if pending > 0 { diff --git a/ipn/auditlog/auditlog_test.go b/ipn/auditlog/auditlog_test.go index 5e499cc67..756168f11 100644 --- a/ipn/auditlog/auditlog_test.go +++ b/ipn/auditlog/auditlog_test.go @@ -7,6 +7,7 @@ import ( "context" "errors" "fmt" + "strings" "sync" "testing" "time" @@ -370,6 +371,32 @@ func TestEnqueueBeforeSetProfileID(t *testing.T) { } } +// TestStartBeforeSetProfileID tests that a logger can be started for a profile +// that has no ID yet, and that it sends logs once the ID is set. +func TestStartBeforeSetProfileID(t *testing.T) { + c := qt.New(t) + mockTransport := newMockTransport(nil) + al := loggerForTest(t, Opts{ + RetryLimit: 100, + Logf: func(format string, args ...any) { + t.Logf(format, args...) + if strings.Contains(format, "[unexpected]") { + t.Errorf("unexpected log: "+format, args...) + } + }, + Store: NewLogStore(&mem.Store{}), + }) + + c.Assert(al.Start(mockTransport), qt.IsNil) + c.Assert(al.SetProfileID("test"), qt.IsNil) + c.Assert(al.Enqueue(tailcfg.AuditNodeDisconnect, "log"), qt.IsNil) + al.FlushAndStop(context.Background()) + + if gotSent, wantSent := mockTransport.sentCount(), 1; gotSent != wantSent { + t.Fatalf("sent: got %d, want %d", gotSent, wantSent) + } +} + // TestLogStoring tests that audit logs are persisted sorted by timestamp, oldest to newest func TestLogSorting(t *testing.T) { c := qt.New(t)