package audit import ( "bytes" "strings" "testing" "time" "errors" "github.com/hashicorp/vault/helper/salt" "github.com/hashicorp/vault/logical" ) func TestFormatJSONx_formatRequest(t *testing.T) { cases := map[string]struct { Auth *logical.Auth Req *logical.Request Err error Prefix string Result string Expected string }{ "auth, request": { &logical.Auth{ClientToken: "foo", Policies: []string{"root"}}, &logical.Request{ Operation: logical.UpdateOperation, Path: "/foo", Connection: &logical.Connection{ RemoteAddr: "127.0.0.1", }, WrapInfo: &logical.RequestWrapInfo{ TTL: 60 * time.Second, }, Headers: map[string][]string{ "foo": []string{"bar"}, }, }, errors.New("this is an error"), "", "", `rootthis is an errorbarupdate/foo127.0.0.160request`, }, "auth, request with prefix": { &logical.Auth{ClientToken: "foo", Policies: []string{"root"}}, &logical.Request{ Operation: logical.UpdateOperation, Path: "/foo", Connection: &logical.Connection{ RemoteAddr: "127.0.0.1", }, WrapInfo: &logical.RequestWrapInfo{ TTL: 60 * time.Second, }, Headers: map[string][]string{ "foo": []string{"bar"}, }, }, errors.New("this is an error"), "", "@cee: ", `rootthis is an errorbarupdate/foo127.0.0.160request`, }, } for name, tc := range cases { var buf bytes.Buffer formatter := AuditFormatter{ AuditFormatWriter: &JSONxFormatWriter{ Prefix: tc.Prefix, }, } salter, _ := salt.NewSalt(nil, nil) config := FormatterConfig{ Salt: salter, OmitTime: true, } if err := formatter.FormatRequest(&buf, config, tc.Auth, tc.Req, tc.Err); err != nil { t.Fatalf("bad: %s\nerr: %s", name, err) } if !strings.HasPrefix(buf.String(), tc.Prefix) { t.Fatalf("no prefix: %s \n log: %s\nprefix: %s", name, tc.Result, tc.Prefix) } if !strings.HasSuffix(strings.TrimSpace(buf.String()), string(tc.Expected)) { t.Fatalf( "bad: %s\nResult:\n\n'%s'\n\nExpected:\n\n'%s'", name, strings.TrimSpace(buf.String()), string(tc.Expected)) } } }