| 1 | package browserops |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | func TestDiagnosticsReadOnlyBoundedAndAttributed(t *testing.T) { |
| 15 | file := ledgerFile{Version: 1, Operations: map[string]*Operation{}} |
| 16 | for i := range 205 { |
| 17 | id := fmt.Sprintf("op-%03d", i) |
| 18 | file.Operations[id] = &Operation{ID: id, DiagnosticScope: "source", State: StateReserved, ReservedAt: time.Unix(int64(i), 0), Generation: "DO-NOT-EXPORT-GRANT", DocumentToken: "DO-NOT-EXPORT-TOKEN", Reason: "password=DO-NOT-EXPORT-PASSWORD"} |
| 19 | } |
| 20 | file.Operations["foreign"] = &Operation{ID: "FOREIGN-OP", DiagnosticScope: "other", State: StateUnknown} |
| 21 | file.Operations["legacy"] = &Operation{ID: "LEGACY-OP", SessionID: "source", State: StateUnknown} |
| 22 | file.Operations["op-204"].TabID = strings.Repeat("x", 1<<20) |
| 23 | path := filepath.Join(t.TempDir(), "operations.json") |
| 24 | before, _ := json.Marshal(file) |
| 25 | if err := os.WriteFile(path, before, 0600); err != nil { |
| 26 | t.Fatal(err) |
| 27 | } |
| 28 | got, err := ReadDiagnostics(path, "source") |
| 29 | if err != nil { |
| 30 | t.Fatal(err) |
| 31 | } |
| 32 | if !got.Available || !got.Truncated || !got.FieldsTruncated || got.Matched != 205 || len(got.Operations) != 200 || got.Operations[0].OperationID != "op-204" || len(got.Operations[0].TabID) != 160 { |
| 33 | t.Fatalf("unexpected snapshot: %+v", got) |
| 34 | } |
| 35 | for _, op := range got.Operations { |
| 36 | if op.State != StateReserved { |
| 37 | t.Fatalf("export changed state: %+v", op) |
| 38 | } |
| 39 | } |
| 40 | after, _ := os.ReadFile(path) |
| 41 | if !bytes.Equal(before, after) { |
| 42 | t.Fatal("export rewrote ledger") |
| 43 | } |
| 44 | encoded, _ := json.Marshal(got) |
| 45 | for _, secret := range []string{"DO-NOT-EXPORT", "FOREIGN-OP", "LEGACY-OP"} { |
| 46 | if strings.Contains(string(encoded), secret) { |
| 47 | t.Fatalf("export leaked %s", secret) |
| 48 | } |
| 49 | } |
| 50 | l := &Ledger{file: file} |
| 51 | if got := l.Diagnostics(""); got.Available || len(got.Operations) != 0 { |
| 52 | t.Fatal("empty identity must fail closed") |
| 53 | } |
| 54 | if got := l.Diagnostics("missing"); !got.Available || len(got.Operations) != 0 { |
| 55 | t.Fatal("incorrect filtering") |
| 56 | } |
| 57 | } |
| 58 |