188 lines
8.2 KiB
Go
188 lines
8.2 KiB
Go
package leaktrace
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/backend/config"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/usecase/assessment"
|
|
)
|
|
|
|
type tracerFake struct {
|
|
result assessment.LeakTraceResult
|
|
err error
|
|
command assessment.LeakTraceCommand
|
|
calls int
|
|
}
|
|
|
|
func (tracer *tracerFake) Trace(_ context.Context, command assessment.LeakTraceCommand) (assessment.LeakTraceResult, error) {
|
|
tracer.calls++
|
|
tracer.command = command
|
|
return tracer.result, tracer.err
|
|
}
|
|
|
|
func TestParseTakesTheTextFromAFileOrStandardInputAndAnOperatorHandle(t *testing.T) {
|
|
command, err := Parse([]string{"search", "--actor", "operator:night", "--file", "leak.txt"})
|
|
if err != nil || command.File != "leak.txt" || command.Actor != "operator:night" || command.Stdin {
|
|
t.Fatalf("Parse(file) = %+v, %v", command, err)
|
|
}
|
|
command, err = Parse([]string{"search", "--actor", "operator:night", "--stdin", "--code", "7k3qd 9xm2t"})
|
|
if err != nil || !command.Stdin || command.Code != "7k3qd 9xm2t" {
|
|
t.Fatalf("Parse(stdin and code) = %+v, %v", command, err)
|
|
}
|
|
// A code read from a screenshot by eye is enough on its own.
|
|
if _, err := Parse([]string{"search", "--actor", "operator:night", "--code", "7K3QD-9XM2T"}); err != nil {
|
|
t.Fatalf("Parse(code only) error = %v", err)
|
|
}
|
|
for _, args := range [][]string{
|
|
nil,
|
|
{"find"},
|
|
{"search"},
|
|
{"search", "--file", "leak.txt"},
|
|
{"search", "--actor", "alice", "--file", "leak.txt"},
|
|
{"search", "--actor", "operator:night"},
|
|
{"search", "--actor", "operator:night", "--file", "leak.txt", "--stdin"},
|
|
{"search", "--actor", "operator:night", "--code", "NOT A CODE"},
|
|
{"search", "--actor", "operator:night", "--file", "leak.txt", "extra"},
|
|
} {
|
|
if _, err := Parse(args); err == nil {
|
|
t.Errorf("Parse(%v) accepted invalid arguments", args)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRunValidatesArgumentsBeforeReadingTheEnvironmentAndNeverEchoesTheSecret(t *testing.T) {
|
|
lookup := func(string) (string, bool) {
|
|
t.Fatal("environment read before arguments were validated")
|
|
return "", false
|
|
}
|
|
if err := Run(context.Background(), []string{"search"}, lookup, strings.NewReader(""), &bytes.Buffer{}); err == nil {
|
|
t.Fatal("Run(invalid arguments) succeeded")
|
|
}
|
|
args := []string{"search", "--actor", "operator:night", "--stdin"}
|
|
var noDatabase config.LookupEnv = func(string) (string, bool) { return "", false }
|
|
if err := Run(context.Background(), args, noDatabase, strings.NewReader("leaked text"), &bytes.Buffer{}); err == nil || !strings.Contains(err.Error(), "DATABASE_URL") {
|
|
t.Fatalf("Run(no database) error = %v, want a DATABASE_URL message", err)
|
|
}
|
|
// A secret that the server could not have used makes every code unreadable, so the command refuses it.
|
|
const shortSecret = "too-short-secret"
|
|
var weakSecret config.LookupEnv = func(key string) (string, bool) {
|
|
switch key {
|
|
case "DATABASE_URL":
|
|
return "postgres://operator@localhost/lincodex", true
|
|
case "IDENTITY_KEY_SECRET":
|
|
return shortSecret, true
|
|
default:
|
|
return "", false
|
|
}
|
|
}
|
|
err := Run(context.Background(), args, weakSecret, strings.NewReader("leaked text"), &bytes.Buffer{})
|
|
if err == nil || !strings.Contains(err.Error(), "IDENTITY_KEY_SECRET") || strings.Contains(err.Error(), shortSecret) {
|
|
t.Fatalf("Run(weak secret) error = %v, want a message that does not echo the secret", err)
|
|
}
|
|
var noSecret config.LookupEnv = func(key string) (string, bool) {
|
|
if key == "DATABASE_URL" {
|
|
return "postgres://operator@localhost/lincodex", true
|
|
}
|
|
return "", false
|
|
}
|
|
if err := Run(context.Background(), args, noSecret, strings.NewReader("leaked text"), &bytes.Buffer{}); err == nil || !strings.Contains(err.Error(), "IDENTITY_KEY_SECRET") {
|
|
t.Fatalf("Run(no secret) error = %v, want an IDENTITY_KEY_SECRET message", err)
|
|
}
|
|
}
|
|
|
|
func TestTheTextIsReadFromAFileOrStandardInputWithinTheLimit(t *testing.T) {
|
|
path := filepath.Join(t.TempDir(), "leak.txt")
|
|
if err := os.WriteFile(path, []byte("text from a file"), 0o600); err != nil {
|
|
t.Fatalf("write fixture: %v", err)
|
|
}
|
|
fromFile, err := readText(Command{File: path}, strings.NewReader("ignored"))
|
|
if err != nil || fromFile != "text from a file" {
|
|
t.Fatalf("readText(file) = %q, %v", fromFile, err)
|
|
}
|
|
fromStdin, err := readText(Command{Stdin: true}, strings.NewReader("text from stdin"))
|
|
if err != nil || fromStdin != "text from stdin" {
|
|
t.Fatalf("readText(stdin) = %q, %v", fromStdin, err)
|
|
}
|
|
// One byte above the limit of the usecase is read, so an oversize text is refused and not cut.
|
|
oversize, err := readText(Command{Stdin: true}, strings.NewReader(strings.Repeat("a", 1<<20)))
|
|
if err != nil || len(oversize) != maxInputBytes {
|
|
t.Fatalf("readText(oversize) read %d bytes, %v, want %d", len(oversize), err, maxInputBytes)
|
|
}
|
|
if _, err := readText(Command{File: filepath.Join(t.TempDir(), "missing.txt")}, strings.NewReader("")); err == nil {
|
|
t.Fatal("readText(missing file) succeeded")
|
|
}
|
|
if text, err := readText(Command{Code: "7K3QD-9XM2T"}, strings.NewReader("ignored")); err != nil || text != "" {
|
|
t.Fatalf("readText(code only) = %q, %v, want no text", text, err)
|
|
}
|
|
}
|
|
|
|
func TestExecutePrintsTheOutcomeAndNeverTheLeakedText(t *testing.T) {
|
|
const leaked = "SECRET-LEAKED-STATEMENT about a sliding-window limiter"
|
|
attemptID := domain.AssessmentAttemptID(uuid.New())
|
|
found := &tracerFake{result: assessment.LeakTraceResult{
|
|
SearchID: uuid.New(), Status: domain.AssessmentLeakTraceFound, Method: domain.AssessmentLeakTraceInvisibleMark,
|
|
AttemptID: attemptID, Candidates: 1, EvidenceBits: 50, Notes: []string{"the invisible mark of the statement carries one code"},
|
|
}}
|
|
var output bytes.Buffer
|
|
if err := Execute(context.Background(), Command{Actor: "operator:night", Stdin: true}, leaked, found, &output); err != nil {
|
|
t.Fatalf("Execute(found) error = %v", err)
|
|
}
|
|
for _, want := range []string{
|
|
"result: found", "method: invisible_mark", "attempt: " + attemptID.String(), "evidence_bits: 50", "candidates: 1",
|
|
"note: the invisible mark of the statement carries one code", "an employer never sees it", "changes no score, category, or quota",
|
|
} {
|
|
if !strings.Contains(output.String(), want) {
|
|
t.Errorf("output lacks %q:\n%s", want, output.String())
|
|
}
|
|
}
|
|
if strings.Contains(output.String(), "SECRET-LEAKED") || strings.Contains(output.String(), "sliding-window") {
|
|
t.Fatalf("the output quotes the leaked text:\n%s", output.String())
|
|
}
|
|
if found.command.Actor != "operator:night" || found.command.Text != leaked {
|
|
t.Fatalf("command = %+v, want the actor and the text passed on", found.command)
|
|
}
|
|
|
|
notFound := &tracerFake{result: assessment.LeakTraceResult{
|
|
SearchID: uuid.New(), Status: domain.AssessmentLeakTraceNotFound, Notes: []string{"no statement of any real attempt contains this text"},
|
|
}}
|
|
output.Reset()
|
|
if err := Execute(context.Background(), Command{Actor: "operator:night", Stdin: true}, leaked, notFound, &output); err != nil {
|
|
t.Fatalf("Execute(not found) error = %v", err)
|
|
}
|
|
if !strings.Contains(output.String(), "result: not_found") || !strings.Contains(output.String(), "not found is an honest answer") ||
|
|
strings.Contains(output.String(), "attempt:") || strings.Contains(output.String(), "method:") {
|
|
t.Fatalf("not found output:\n%s", output.String())
|
|
}
|
|
}
|
|
|
|
func TestExecuteMapsFailuresToSafeMessages(t *testing.T) {
|
|
const leaked = "SECRET-LEAKED-STATEMENT"
|
|
for name, test := range map[string]struct {
|
|
err error
|
|
want string
|
|
}{
|
|
"a request the usecase refuses": {err: assessment.ErrInvalidLeakTrace, want: "cannot be searched"},
|
|
"an invalid actor": {err: domain.ErrInvalidAssessmentReview, want: "actor is invalid"},
|
|
"a storage failure": {err: errors.New("pq: connection refused for " + leaked), want: "operation failed"},
|
|
} {
|
|
t.Run(name, func(t *testing.T) {
|
|
err := Execute(context.Background(), Command{Actor: "operator:night", Stdin: true}, leaked, &tracerFake{err: test.err}, &bytes.Buffer{})
|
|
if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), leaked) {
|
|
t.Fatalf("Execute() error = %v, want a safe message containing %q", err, test.want)
|
|
}
|
|
})
|
|
}
|
|
if err := Execute(context.Background(), Command{}, "", nil, &bytes.Buffer{}); err == nil {
|
|
t.Fatal("Execute() without a tracer succeeded")
|
|
}
|
|
}
|