Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ Environment variables (prefix `WHENCE_`):
| `WHENCE_QUIET` | `500ms` | silence before a touch is considered done |
| `WHENCE_SWEEP` | `200ms` | how often idle sessions are checked |
| `WHENCE_DEBUG` | `false` | debug logging (same as `-verbose`) |
| `WHENCE_NOTIFIER` | `dbus` | notification backend: `dbus` (desktop) or `log` (log only) |

## Supported tools

Expand Down
4 changes: 4 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ type Config struct {
Quiet time.Duration `envconfig:"QUIET" default:"500ms"`
Sweep time.Duration `envconfig:"SWEEP" default:"200ms"`
Debug bool `envconfig:"DEBUG"`
// Notifier selects the notification backend: "dbus" (default) posts desktop
// notifications; "log" only logs touches — for headless runs and the
// container e2e harness. See internal/notifier.
Notifier string `envconfig:"NOTIFIER" default:"dbus"`
}

// Load reads config from the environment (prefix WHENCE_).
Expand Down
64 changes: 64 additions & 0 deletions internal/notifier/dbus.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package notifier

import (
"fmt"

"github.com/godbus/dbus/v5"
)

const (
dest = "org.freedesktop.Notifications"
opath = "/org/freedesktop/Notifications"
iface = "org.freedesktop.Notifications"
)

// DBus posts desktop notifications via the org.freedesktop.Notifications DBus
// interface. Using DBus directly (instead of notify-send) lets us obtain the
// notification ID so we can dismiss it programmatically once the YubiKey has
// been touched.
type DBus struct{}

// TouchNeeded shows a persistent critical-urgency notification asking the user
// to touch their YubiKey. It never expires automatically; call Close with the
// returned ID once the touch is detected.
func (DBus) TouchNeeded(body string) (uint32, error) {
conn, err := dbus.SessionBus()
if err != nil {
return 0, fmt.Errorf("session bus: %w", err)
}

hints := map[string]dbus.Variant{
"urgency": dbus.MakeVariant(byte(2)), // 2 = critical
}

call := conn.Object(dest, opath).Call(
iface+".Notify", 0,
"Whence Touché", // app_name
uint32(0), // replaces_id (0 = new notification)
"dialog-password", // app_icon
"Touch your YubiKey", // summary
body, // body
[]string{}, // actions
hints, // hints
int32(0), // expire_timeout: 0 = never expire
)
if call.Err != nil {
return 0, call.Err
}
var id uint32
if err := call.Store(&id); err != nil {
return 0, err
}
return id, nil
}

// Close dismisses a notification by the ID returned from TouchNeeded.
// Errors are silently discarded — the notification daemon may have already
// closed it (e.g. the user clicked it away).
func (DBus) Close(id uint32) {
conn, err := dbus.SessionBus()
if err != nil {
return
}
conn.Object(dest, opath).Call(iface+".CloseNotification", 0, id)
}
23 changes: 23 additions & 0 deletions internal/notifier/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package notifier

import "github.com/rs/zerolog/log"

// Log is a Notifier that records touches in the log instead of posting a
// desktop notification. It needs no session bus or notification daemon, which
// makes it the backend the container e2e harness runs in: the harness asserts
// the resolved tool from the log line alone. Handy for headless debugging too.
type Log struct{}

// TouchNeeded logs the pending touch at info level — so it shows without
// -verbose and is greppable by the e2e harness — and returns a zero ID, since
// there is nothing on screen to dismiss later.
func (Log) TouchNeeded(body string) (uint32, error) {
log.Info().Str("touch", body).Msg("touch needed")
return 0, nil
}

// Close logs that the touch finished. The ID is unused: the log backend has no
// on-screen notification to dismiss.
func (Log) Close(uint32) {
log.Info().Msg("touch done")
}
79 changes: 26 additions & 53 deletions internal/notifier/notifier.go
Original file line number Diff line number Diff line change
@@ -1,62 +1,35 @@
// Package notifier sends desktop notifications via the org.freedesktop.Notifications
// DBus interface. Using DBus directly (instead of notify-send) lets us obtain
// the notification ID so we can dismiss it programmatically once the YubiKey
// has been touched.
// Package notifier shows and dismisses "touch your security key" notifications.
//
// A backend is chosen at startup with New: the default DBus backend posts real
// desktop notifications via the org.freedesktop.Notifications interface, while
// the Log backend only writes to the log. The Log backend needs no session bus
// or notification daemon, so it suits headless runs and the container e2e
// harness, which asserts the resolved tool from the log line alone.
package notifier

import (
"fmt"

"github.com/godbus/dbus/v5"
)

const (
dest = "org.freedesktop.Notifications"
opath = "/org/freedesktop/Notifications"
iface = "org.freedesktop.Notifications"
"errors"
)

// TouchNeeded shows a persistent critical-urgency notification asking the user
// to touch their YubiKey. It never expires automatically; call Close with the
// returned ID once the touch is detected.
func TouchNeeded(body string) (uint32, error) {
conn, err := dbus.SessionBus()
if err != nil {
return 0, fmt.Errorf("session bus: %w", err)
}

hints := map[string]dbus.Variant{
"urgency": dbus.MakeVariant(byte(2)), // 2 = critical
}

call := conn.Object(dest, opath).Call(
iface+".Notify", 0,
"Whence Touché", // app_name
uint32(0), // replaces_id (0 = new notification)
"dialog-password", // app_icon
"Touch your YubiKey", // summary
body, // body
[]string{}, // actions
hints, // hints
int32(0), // expire_timeout: 0 = never expire
)
if call.Err != nil {
return 0, call.Err
}
var id uint32
if err := call.Store(&id); err != nil {
return 0, err
}
return id, nil
// Notifier announces a pending security-key touch and later dismisses it.
//
// TouchNeeded posts a notification for body and returns an ID; once the touch
// completes, Close dismisses the notification with that ID. Backends that have
// nothing on screen to dismiss (e.g. Log) may ignore the ID.
type Notifier interface {
TouchNeeded(body string) (uint32, error)
Close(id uint32)
}

// Close dismisses a notification by the ID returned from TouchNeeded.
// Errors are silently discarded — the notification daemon may have already
// closed it (e.g. the user clicked it away).
func Close(id uint32) {
conn, err := dbus.SessionBus()
if err != nil {
return
// New returns the notifier backend named by name: "dbus" for desktop
// notifications, "log" for the log-only backend. Any other name is an error.
func New(name string) (Notifier, error) {
switch name {
case "log":
return Log{}, nil
case "dbus":
return DBus{}, nil
default:
return nil, errors.New("unknown notifier type")
}
conn.Object(dest, opath).Call(iface+".CloseNotification", 0, id)
}
18 changes: 13 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ func (s *session) ready(threshold int, delay time.Duration) bool {
func main() {
cfg, cfgErr := config.Load()
verbose := flag.Bool("verbose", cfg.Debug, "enable debug logging (or set WHENCE_DEBUG=true)")
backend := flag.String("notifier", cfg.Notifier,
`notification backend: "dbus" for desktop notifications, "log" to only log touches (or set WHENCE_NOTIFIER)`)
flag.Parse()

level := zerolog.InfoLevel
Expand All @@ -69,6 +71,11 @@ func main() {
}
defer tr.Close()

ntf, err := notifier.New(*backend)
if err != nil {
log.Fatal().Err(err).Msg("set WHENCE_NOTIFIER to supported value")
}

allRules := rules.All()
sessions := make(map[sessionKey]*session)

Expand All @@ -84,7 +91,7 @@ func main() {
log.Warn().Msg("tracer event stream closed")
return
}
handleEvent(allRules, sessions, ev, cfg.NotifyThreshold, cfg.NotifyDelay)
handleEvent(allRules, sessions, ev, cfg.NotifyThreshold, cfg.NotifyDelay, ntf)

case <-ticker.C:
now := time.Now()
Expand All @@ -93,7 +100,7 @@ func main() {
continue
}
if s.shown {
notifier.Close(s.notifID)
ntf.Close(s.notifID)
log.Debug().Str("kind", key.src.Kind()).Uint32("pid", key.pid).Msg("touch done")
}
delete(sessions, key)
Expand All @@ -103,8 +110,9 @@ func main() {
}

// handleEvent records an I/O and notifies once a session shows sustained
// activity (see session.ready).
func handleEvent(allRules []clsf.Rule, sessions map[sessionKey]*session, ev tracer.Event, threshold int, delay time.Duration) {
// activity (see session.ready). The notifier ntf decides how the touch is
// surfaced — a desktop notification or a log line (see internal/notifier).
func handleEvent(allRules []clsf.Rule, sessions map[sessionKey]*session, ev tracer.Event, threshold int, delay time.Duration, ntf notifier.Notifier) {
key := sessionKey{ev.Source, ev.PID}
s := sessions[key]
now := time.Now()
Expand All @@ -123,7 +131,7 @@ func handleEvent(allRules []clsf.Rule, sessions map[sessionKey]*session, ev trac
body := buildBody(allRules, ev)
log.Debug().Str("kind", ev.Source.Kind()).Uint32("pid", ev.PID).Str("body", body).Msg("touch needed")

id, err := notifier.TouchNeeded(body)
id, err := ntf.TouchNeeded(body)
if err != nil {
log.Warn().Err(err).Msg("send notification")
return
Expand Down
3 changes: 2 additions & 1 deletion main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"testing"
"time"

"github.com/Talgarr/Whence-Touche/internal/notifier"
"github.com/Talgarr/Whence-Touche/internal/tracer"
)

Expand Down Expand Up @@ -90,7 +91,7 @@ func TestHandleEventAccumulates(t *testing.T) {
// A short burst of events, all within the same instant for test purposes:
// count climbs past the threshold but the span stays ~0, so nothing shows.
for i := 0; i < 5; i++ {
handleEvent(nil, sessions, ev, 3, 500*time.Millisecond)
handleEvent(nil, sessions, ev, 3, 500*time.Millisecond, notifier.Log{})
}

s := sessions[sessionKey{ev.Source, ev.PID}]
Expand Down