mirror of
https://github.com/netbirdio/netbird.git
synced 2026-08-06 07:41:27 +02:00
Compare commits
3 Commits
notificati
...
docs/agent
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aad0e7c322 | ||
|
|
b083240374 | ||
|
|
b27ef7ff76 |
@@ -1,6 +1,6 @@
|
||||
# NetBird Agent Guidelines
|
||||
|
||||
**NetBird** is an open-source connectivity platform: a WireGuard®-based overlay
|
||||
**NetBird** is an open source connectivity platform: a WireGuard®-based overlay
|
||||
network with a control plane. The **agent** (`client/`) runs on user machines as
|
||||
a privileged daemon and manages the WireGuard interface, routing, firewall, and
|
||||
DNS. **Management** (`management/`) is the control plane and REST/gRPC API,
|
||||
|
||||
@@ -478,7 +478,7 @@ go test -race ./client/internal/dns/...
|
||||
|
||||
## Checklist before submitting a PR
|
||||
|
||||
As a critical network service and open-source project, we must enforce a few
|
||||
As a critical network service and open source project, we must enforce a few
|
||||
things before submitting a pull request. The
|
||||
[pull request template](/.github/pull_request_template.md) mirrors this list —
|
||||
fill it in rather than deleting it.
|
||||
|
||||
@@ -130,7 +130,7 @@ In November 2022, NetBird joined the [StartUpSecure program](https://www.forschu
|
||||

|
||||
|
||||
### Acknowledgements
|
||||
We build on open-source technologies like [WireGuard®](https://www.wireguard.com/), [Pion ICE](https://github.com/pion/ice), and [Rosenpass](https://rosenpass.eu). We greatly appreciate the work these projects are doing, and we'd love it if you could support them too (e.g., by starring or contributing).
|
||||
We build on open source technologies like [WireGuard®](https://www.wireguard.com/), [Pion ICE](https://github.com/pion/ice), and [Rosenpass](https://rosenpass.eu). We greatly appreciate the work these projects are doing, and we'd love it if you could support them too (e.g., by starring or contributing).
|
||||
|
||||
### Legal
|
||||
This repository is licensed under the BSD-3-Clause license, which applies to all parts of the repository except for the directories management/, signal/ and relay/.
|
||||
|
||||
@@ -14,7 +14,7 @@ Report security issues one of these two ways:
|
||||
on this repository. This is the preferred route: it keeps the discussion, the draft advisory, and the credit in one place.
|
||||
- **Email** — `security@netbird.io`.
|
||||
|
||||
If the finding affects NetBird Cloud or our hosted infrastructure rather than the open-source code, email us rather than
|
||||
If the finding affects NetBird Cloud or our hosted infrastructure rather than the open source code, email us rather than
|
||||
filing a repository report.
|
||||
|
||||
### What to include
|
||||
|
||||
@@ -11,11 +11,10 @@ import (
|
||||
// emits.
|
||||
|
||||
// Metadata keys attached by the daemon to session-warning SystemEvents.
|
||||
// The notification text itself travels as a message key (see
|
||||
// proto.UserMsgSessionExpiresIn); these keys carry the structured deadline
|
||||
// the UI needs for its own countdown label, and disambiguate the
|
||||
// T-WarningLead notification from the T-FinalWarningLead fallback that
|
||||
// auto-opens the SessionAboutToExpire dialog.
|
||||
// The UI tray reads these to build a locale-aware notification without
|
||||
// relying on the daemon's locale-less UserMessage string, and to
|
||||
// disambiguate the T-WarningLead notification from the T-FinalWarningLead
|
||||
// fallback that auto-opens the SessionAboutToExpire dialog.
|
||||
const (
|
||||
// MetaSessionWarning is set to "true" on both warning events (T-10 and
|
||||
// T-2) so the UI can detect a session-warning SystemEvent without
|
||||
@@ -37,9 +36,10 @@ const (
|
||||
// MetaSessionDeadlineRejected is attached to the ERROR/AUTHENTICATION
|
||||
// SystemEvent the daemon emits when it discards a deadline from the
|
||||
// management server (pre-epoch, too far in the future, or past the
|
||||
// clock-skew tolerance). The value is the rejection reason string,
|
||||
// which is diagnostic only: the user-facing text travels as
|
||||
// proto.UserMsgSessionDeadlineReject.
|
||||
// clock-skew tolerance). The value is the rejection reason string.
|
||||
// userMessage is left empty; the UI detects the event via this key
|
||||
// and builds a localized notification — same pattern as the session
|
||||
// warnings above.
|
||||
MetaSessionDeadlineRejected = "session_deadline_rejected"
|
||||
)
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
cProto "github.com/netbirdio/netbird/client/proto"
|
||||
nbstatus "github.com/netbirdio/netbird/client/status"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -81,7 +80,7 @@ type StatusRecorder interface {
|
||||
severity cProto.SystemEvent_Severity,
|
||||
category cProto.SystemEvent_Category,
|
||||
message string,
|
||||
userMessage *cProto.UserMessage,
|
||||
userMessage string,
|
||||
metadata map[string]string,
|
||||
)
|
||||
}
|
||||
@@ -377,22 +376,7 @@ func publishWarning(recorder StatusRecorder, deadline time.Time, final bool) {
|
||||
cProto.SystemEvent_CRITICAL,
|
||||
cProto.SystemEvent_AUTHENTICATION,
|
||||
message,
|
||||
warningUserMessage(deadline),
|
||||
"",
|
||||
meta,
|
||||
)
|
||||
}
|
||||
|
||||
// warningUserMessage builds the localizable body for a session warning. The
|
||||
// remaining time is rendered here rather than in the UI so every consumer of the
|
||||
// event agrees on it; a deadline that is already gone (a warning delivered late)
|
||||
// drops to the variant without a countdown.
|
||||
func warningUserMessage(deadline time.Time) *cProto.UserMessage {
|
||||
remaining := time.Until(deadline)
|
||||
if remaining <= 0 {
|
||||
return cProto.NewUserMessage(cProto.UserMsgSessionExpiresSoon).
|
||||
WithTitle(cProto.TitleSessionWarning)
|
||||
}
|
||||
return cProto.NewUserMessage(cProto.UserMsgSessionExpiresIn,
|
||||
cProto.ArgRemaining, nbstatus.HumaniseDuration(remaining)).
|
||||
WithTitle(cProto.TitleSessionWarning)
|
||||
}
|
||||
|
||||
@@ -34,9 +34,6 @@ type event struct {
|
||||
severity cProto.SystemEvent_Severity
|
||||
category cProto.SystemEvent_Category
|
||||
message string
|
||||
msgKey cProto.UserMessageKey
|
||||
titleKey cProto.UserMessageKey
|
||||
msgArgs map[string]string
|
||||
meta map[string]string
|
||||
}
|
||||
|
||||
@@ -65,7 +62,7 @@ func (r *fakeRecorder) PublishEvent(
|
||||
severity cProto.SystemEvent_Severity,
|
||||
category cProto.SystemEvent_Category,
|
||||
message string,
|
||||
userMessage *cProto.UserMessage,
|
||||
_ string,
|
||||
metadata map[string]string,
|
||||
) {
|
||||
r.mu.Lock()
|
||||
@@ -75,9 +72,6 @@ func (r *fakeRecorder) PublishEvent(
|
||||
severity: severity,
|
||||
category: category,
|
||||
message: message,
|
||||
msgKey: userMessage.Key(),
|
||||
titleKey: userMessage.TitleKey(),
|
||||
msgArgs: userMessage.Args(),
|
||||
meta: metadata,
|
||||
})
|
||||
}
|
||||
@@ -192,33 +186,6 @@ func TestWarningFiresOnceWithinLeadWindow(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The UI localizes the warning body from the key rather than from the daemon's
|
||||
// English text, so a warning that ships no key would silently regress to English.
|
||||
func TestWarningCarriesLocalizableMessage(t *testing.T) {
|
||||
r := &fakeRecorder{}
|
||||
w := newWatcher(50*time.Millisecond, r)
|
||||
defer w.Close()
|
||||
|
||||
_ = w.Update(time.Now().Add(80 * time.Millisecond))
|
||||
|
||||
events := waitForEvents(t, r, 2)
|
||||
warning := events[1]
|
||||
if !warning.isWarning() {
|
||||
t.Fatalf("event[1] should be a warning publish, got %+v", warning)
|
||||
}
|
||||
if warning.msgKey != cProto.UserMsgSessionExpiresIn {
|
||||
t.Errorf("warning message key = %q, want %q", warning.msgKey, cProto.UserMsgSessionExpiresIn)
|
||||
}
|
||||
if warning.titleKey != cProto.TitleSessionWarning {
|
||||
t.Errorf("warning title key = %q, want %q", warning.titleKey, cProto.TitleSessionWarning)
|
||||
}
|
||||
// The remaining time is rendered at publish time so every consumer of the
|
||||
// event agrees on it; the exact value depends on timer slack.
|
||||
if remaining := warning.msgArgs[cProto.ArgRemaining]; remaining == "" {
|
||||
t.Errorf("warning is missing the %q argument, args=%v", cProto.ArgRemaining, warning.msgArgs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWarningFiresImmediatelyWhenAlreadyInsideWindow(t *testing.T) {
|
||||
r := &fakeRecorder{}
|
||||
w := newWatcher(time.Hour, r) // lead > delta => fire immediately
|
||||
|
||||
@@ -163,7 +163,7 @@ func (c *ConnectClient) run(mobileDependency MobileDependency, runningChan chan
|
||||
rec.PublishEvent(
|
||||
cProto.SystemEvent_CRITICAL, cProto.SystemEvent_SYSTEM,
|
||||
"panic occurred",
|
||||
cProto.NewUserMessage(cProto.UserMsgPanic),
|
||||
"The Netbird service panicked. Please restart the service and submit a bug report with the client logs.",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
)
|
||||
|
||||
func getInterfaceIndex(interfaceName string) (int, error) {
|
||||
iface, err := net.InterfaceByName(interfaceName)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("lookup interface %q: %w", interfaceName, err)
|
||||
}
|
||||
|
||||
return iface.Index, nil
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"net"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetInterfaceIndexExisting(t *testing.T) {
|
||||
interfaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
t.Fatalf("list network interfaces: %v", err)
|
||||
}
|
||||
if len(interfaces) == 0 {
|
||||
t.Fatal("expected at least one network interface")
|
||||
}
|
||||
|
||||
iface := interfaces[0]
|
||||
index, err := getInterfaceIndex(iface.Name)
|
||||
if err != nil {
|
||||
t.Fatalf("look up existing interface %q: %v", iface.Name, err)
|
||||
}
|
||||
if index != iface.Index {
|
||||
t.Fatalf("expected interface index %d, got %d", iface.Index, index)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetInterfaceIndexMissing(t *testing.T) {
|
||||
index, err := getInterfaceIndex("netbird-interface-that-does-not-exist")
|
||||
if index != 0 {
|
||||
t.Fatalf("expected missing interface index to be 0, got %d", index)
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("expected missing interface lookup to return an error")
|
||||
}
|
||||
}
|
||||
@@ -1134,7 +1134,7 @@ func (s *DefaultServer) projectHealthy(p *nsGroupProj, servers []netip.AddrPort)
|
||||
proto.SystemEvent_INFO,
|
||||
proto.SystemEvent_DNS,
|
||||
"Nameserver group recovered",
|
||||
proto.NewUserMessage(proto.UserMsgDNSRecovered),
|
||||
"DNS servers are reachable again.",
|
||||
map[string]string{"upstreams": joinAddrPorts(servers)},
|
||||
)
|
||||
p.warningActive = false
|
||||
@@ -1157,7 +1157,7 @@ func (s *DefaultServer) projectUnhealthy(p *nsGroupProj, servers []netip.AddrPor
|
||||
proto.SystemEvent_WARNING,
|
||||
proto.SystemEvent_DNS,
|
||||
"Nameserver group unreachable",
|
||||
proto.NewUserMessage(proto.UserMsgDNSUnreachable),
|
||||
"Unable to reach one or more DNS servers. This might affect your ability to connect to some services.",
|
||||
map[string]string{"upstreams": joinAddrPorts(servers)},
|
||||
)
|
||||
p.warningActive = true
|
||||
|
||||
@@ -130,3 +130,8 @@ func GetClientPrivate(iface privateClientIface, upstreamIP netip.Addr, dialTimeo
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func getInterfaceIndex(interfaceName string) (int, error) {
|
||||
iface, err := net.InterfaceByName(interfaceName)
|
||||
return iface.Index, err
|
||||
}
|
||||
|
||||
@@ -1074,7 +1074,7 @@ func (e *Engine) handleSync(update *mgmProto.SyncResponse) error {
|
||||
return err
|
||||
}
|
||||
|
||||
e.statusRecorder.PublishEvent(cProto.SystemEvent_INFO, cProto.SystemEvent_SYSTEM, "Network map updated", nil, nil)
|
||||
e.statusRecorder.PublishEvent(cProto.SystemEvent_INFO, cProto.SystemEvent_SYSTEM, "Network map updated", "", nil)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -57,8 +57,7 @@ func (e *Engine) ApplySessionDeadline(ts *timestamppb.Timestamp) {
|
||||
cProto.SystemEvent_ERROR,
|
||||
cProto.SystemEvent_AUTHENTICATION,
|
||||
"session deadline rejected",
|
||||
cProto.NewUserMessage(cProto.UserMsgSessionDeadlineReject).
|
||||
WithTitle(cProto.TitleSessionDeadlineReject),
|
||||
"",
|
||||
map[string]string{sessionwatch.MetaSessionDeadlineRejected: err.Error()},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1281,15 +1281,12 @@ func (d *Status) numOfPeers() int {
|
||||
return len(d.peers) + len(d.offlinePeers)
|
||||
}
|
||||
|
||||
// PublishEvent adds an event to the queue and distributes it to all subscribers.
|
||||
// msg is the English log-facing description; userMsg is the localizable
|
||||
// user-facing message, or nil for an internal control event that must not
|
||||
// surface as a notification.
|
||||
// PublishEvent adds an event to the queue and distributes it to all subscribers
|
||||
func (d *Status) PublishEvent(
|
||||
severity proto.SystemEvent_Severity,
|
||||
category proto.SystemEvent_Category,
|
||||
msg string,
|
||||
userMsg *proto.UserMessage,
|
||||
userMsg string,
|
||||
metadata map[string]string,
|
||||
) {
|
||||
event := &proto.SystemEvent{
|
||||
@@ -1297,10 +1294,7 @@ func (d *Status) PublishEvent(
|
||||
Severity: severity,
|
||||
Category: category,
|
||||
Message: msg,
|
||||
UserMessage: userMsg.Text(),
|
||||
MessageKey: string(userMsg.Key()),
|
||||
MessageArgs: userMsg.Args(),
|
||||
TitleKey: string(userMsg.TitleKey()),
|
||||
UserMessage: userMsg,
|
||||
Metadata: metadata,
|
||||
Timestamp: timestamppb.Now(),
|
||||
}
|
||||
|
||||
@@ -403,7 +403,7 @@ func (w *Watcher) connectEvent(route *route.Route) {
|
||||
proto.SystemEvent_INFO,
|
||||
proto.SystemEvent_NETWORK,
|
||||
"Default route added",
|
||||
proto.NewUserMessage(proto.UserMsgExitNodeConnected),
|
||||
"Exit node connected.",
|
||||
meta,
|
||||
)
|
||||
}
|
||||
@@ -423,7 +423,7 @@ func (w *Watcher) disconnectEvent(route *route.Route, rsn reason) {
|
||||
|
||||
var severity proto.SystemEvent_Severity
|
||||
var message string
|
||||
var userMessage *proto.UserMessage
|
||||
var userMessage string
|
||||
meta := make(map[string]string)
|
||||
|
||||
if route != nil {
|
||||
@@ -435,22 +435,22 @@ func (w *Watcher) disconnectEvent(route *route.Route, rsn reason) {
|
||||
case reasonShutdown:
|
||||
severity = proto.SystemEvent_INFO
|
||||
message = "Default route removed"
|
||||
userMessage = proto.NewUserMessage(proto.UserMsgExitNodeDisconnected)
|
||||
userMessage = "Exit node disconnected."
|
||||
case reasonRouteUpdate:
|
||||
severity = proto.SystemEvent_INFO
|
||||
message = "Default route updated due to configuration change"
|
||||
case reasonPeerUpdate:
|
||||
severity = proto.SystemEvent_WARNING
|
||||
message = "Default route disconnected due to peer unreachability"
|
||||
userMessage = proto.NewUserMessage(proto.UserMsgExitNodeConnectionLost)
|
||||
userMessage = "Exit node connection lost. Your internet access might be affected."
|
||||
case reasonHA:
|
||||
severity = proto.SystemEvent_INFO
|
||||
message = "Default route disconnected due to high availability change"
|
||||
userMessage = proto.NewUserMessage(proto.UserMsgExitNodeHAChange)
|
||||
userMessage = "Exit node disconnected due to high availability change."
|
||||
default:
|
||||
severity = proto.SystemEvent_ERROR
|
||||
message = "Default route disconnected for unknown reasons"
|
||||
userMessage = proto.NewUserMessage(proto.UserMsgExitNodeDisconnectedUnknown)
|
||||
userMessage = "Exit node disconnected for unknown reasons."
|
||||
}
|
||||
|
||||
w.statusRecorder.PublishEvent(
|
||||
|
||||
@@ -94,7 +94,7 @@ func (m *Manager) CheckUpdateSuccess(ctx context.Context) {
|
||||
cProto.SystemEvent_ERROR,
|
||||
cProto.SystemEvent_SYSTEM,
|
||||
"Auto-update failed",
|
||||
cProto.NewUserMessage(cProto.UserMsgUpdateFailed, cProto.ArgReason, reason),
|
||||
fmt.Sprintf("Auto-update failed: %s", reason),
|
||||
nil,
|
||||
)
|
||||
}
|
||||
@@ -115,7 +115,7 @@ func (m *Manager) CheckUpdateSuccess(ctx context.Context) {
|
||||
cProto.SystemEvent_INFO,
|
||||
cProto.SystemEvent_SYSTEM,
|
||||
"Auto-update completed",
|
||||
cProto.NewUserMessage(cProto.UserMsgUpdateCompleted, cProto.ArgVersion, m.currentVersion),
|
||||
fmt.Sprintf("Your NetBird Client was auto-updated to version %s", m.currentVersion),
|
||||
nil,
|
||||
)
|
||||
return
|
||||
@@ -272,7 +272,7 @@ func (m *Manager) NotifyUI() {
|
||||
cProto.SystemEvent_INFO,
|
||||
cProto.SystemEvent_SYSTEM,
|
||||
"New version available",
|
||||
nil,
|
||||
"",
|
||||
map[string]string{"new_version_available": latestVersion.String()},
|
||||
)
|
||||
return
|
||||
@@ -283,7 +283,7 @@ func (m *Manager) NotifyUI() {
|
||||
cProto.SystemEvent_INFO,
|
||||
cProto.SystemEvent_SYSTEM,
|
||||
"New version available",
|
||||
nil,
|
||||
"",
|
||||
map[string]string{"new_version_available": pendingVersion.String(), "enforced": "true"},
|
||||
)
|
||||
}
|
||||
@@ -384,7 +384,7 @@ func (m *Manager) handleUpdate(ctx context.Context) {
|
||||
cProto.SystemEvent_INFO,
|
||||
cProto.SystemEvent_SYSTEM,
|
||||
"New version available",
|
||||
nil,
|
||||
"",
|
||||
map[string]string{"new_version_available": updateVersion.String()},
|
||||
)
|
||||
return
|
||||
@@ -401,7 +401,7 @@ func (m *Manager) handleUpdate(ctx context.Context) {
|
||||
cProto.SystemEvent_INFO,
|
||||
cProto.SystemEvent_SYSTEM,
|
||||
"New version available",
|
||||
nil,
|
||||
"",
|
||||
map[string]string{"new_version_available": updateVersion.String(), "enforced": "true"},
|
||||
)
|
||||
}
|
||||
@@ -411,14 +411,14 @@ func (m *Manager) install(ctx context.Context, pendingVersion *v.Version) error
|
||||
cProto.SystemEvent_CRITICAL,
|
||||
cProto.SystemEvent_SYSTEM,
|
||||
"Updating client",
|
||||
cProto.NewUserMessage(cProto.UserMsgUpdateInstalling),
|
||||
"Installing update now.",
|
||||
nil,
|
||||
)
|
||||
m.statusRecorder.PublishEvent(
|
||||
cProto.SystemEvent_CRITICAL,
|
||||
cProto.SystemEvent_SYSTEM,
|
||||
"",
|
||||
nil,
|
||||
"",
|
||||
map[string]string{"progress_window": "show", "version": pendingVersion.String()},
|
||||
)
|
||||
|
||||
@@ -441,7 +441,7 @@ func (m *Manager) install(ctx context.Context, pendingVersion *v.Version) error
|
||||
cProto.SystemEvent_ERROR,
|
||||
cProto.SystemEvent_SYSTEM,
|
||||
"Auto-update failed",
|
||||
cProto.NewUserMessage(cProto.UserMsgUpdateFailed, cProto.ArgReason, err.Error()),
|
||||
fmt.Sprintf("Auto-update failed: %v", err),
|
||||
nil,
|
||||
)
|
||||
return err
|
||||
|
||||
@@ -158,19 +158,13 @@ func (c *Client) Run(fd int32, interfaceName string, envList *EnvList) error {
|
||||
defer c.ctxCancel()
|
||||
c.ctxCancelLock.Unlock()
|
||||
|
||||
// No login pre-flight here. The engine's own loginToManagement (connect.go) performs
|
||||
// the authoritative Login immediately before the first Sync, so a LoginSync() call at
|
||||
// this point only duplicated it — costing two extra Login RPCs (IsLoginRequired +
|
||||
// Login) on every engine start, since IsLoginRequired is itself a full Login RPC.
|
||||
//
|
||||
// Auth failures still reach the caller through the engine path: loginToManagement
|
||||
// returns PermissionDenied, which marks the shared status recorder
|
||||
// (MarkManagementDisconnected) and fires ClientStop → onDisconnected, where
|
||||
// IsLoginRequiredCached() reports login-required. The error is also returned out of Run().
|
||||
//
|
||||
// A pre-flight was also actively harmful when the server is unreachable: its 2-minute
|
||||
// backoff blocked the start and then reported "login required" for what was really a
|
||||
// timeout. The engine instead keeps retrying and recovers when the server returns.
|
||||
auth := NewAuthWithConfig(ctx, cfg)
|
||||
err = auth.LoginSync()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Infof("Auth successful")
|
||||
// todo do not throw error in case of cancelled context
|
||||
ctx = internal.CtxInitState(ctx)
|
||||
c.onHostDnsFn = func([]string) {}
|
||||
|
||||
@@ -222,36 +222,17 @@ func (a *Auth) Login(resultListener ErrListener, urlOpener URLOpener, forceDevic
|
||||
// LoginWithDeviceName performs interactive login with device authentication support
|
||||
// The deviceName parameter allows specifying a custom device name (required for tvOS)
|
||||
func (a *Auth) LoginWithDeviceName(resultListener ErrListener, urlOpener URLOpener, forceDeviceAuth bool, deviceName string) {
|
||||
a.startLogin(resultListener, urlOpener, forceDeviceAuth, deviceName, false)
|
||||
}
|
||||
|
||||
// LoginInteractive performs the same interactive login as LoginWithDeviceName but skips the
|
||||
// IsLoginRequired() pre-flight and goes straight to the browser / device-code flow.
|
||||
//
|
||||
// IsLoginRequired() is itself a full Login RPC against the management server, so when the
|
||||
// caller has ALREADY established that login is required it is a pure duplicate. On iOS the
|
||||
// main app decides to show the browser based on its own isLoginRequired() check and then
|
||||
// calls straight into this method, so re-asking the server would add another Login RPC to
|
||||
// every interactive login.
|
||||
//
|
||||
// Use LoginWithDeviceName when the auth state is unknown and a silent (browser-less) login
|
||||
// must still be possible; use this when the browser is going to be shown regardless.
|
||||
func (a *Auth) LoginInteractive(resultListener ErrListener, urlOpener URLOpener, forceDeviceAuth bool, deviceName string) {
|
||||
a.startLogin(resultListener, urlOpener, forceDeviceAuth, deviceName, true)
|
||||
}
|
||||
|
||||
func (a *Auth) startLogin(resultListener ErrListener, urlOpener URLOpener, forceDeviceAuth bool, deviceName string, skipLoginCheck bool) {
|
||||
if resultListener == nil {
|
||||
log.Errorf("startLogin: resultListener is nil")
|
||||
log.Errorf("LoginWithDeviceName: resultListener is nil")
|
||||
return
|
||||
}
|
||||
if urlOpener == nil {
|
||||
log.Errorf("startLogin: urlOpener is nil")
|
||||
log.Errorf("LoginWithDeviceName: urlOpener is nil")
|
||||
resultListener.OnError(fmt.Errorf("urlOpener is nil"))
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
err := a.login(urlOpener, forceDeviceAuth, deviceName, skipLoginCheck)
|
||||
err := a.login(urlOpener, forceDeviceAuth, deviceName)
|
||||
if err != nil {
|
||||
resultListener.OnError(err)
|
||||
} else {
|
||||
@@ -260,7 +241,7 @@ func (a *Auth) startLogin(resultListener ErrListener, urlOpener URLOpener, force
|
||||
}()
|
||||
}
|
||||
|
||||
func (a *Auth) login(urlOpener URLOpener, forceDeviceAuth bool, deviceName string, skipLoginCheck bool) error {
|
||||
func (a *Auth) login(urlOpener URLOpener, forceDeviceAuth bool, deviceName string) error {
|
||||
// Create context with device name if provided
|
||||
ctx := a.ctx
|
||||
if deviceName != "" {
|
||||
@@ -274,13 +255,10 @@ func (a *Auth) login(urlOpener URLOpener, forceDeviceAuth bool, deviceName strin
|
||||
}
|
||||
defer authClient.Close()
|
||||
|
||||
// check if we need to generate JWT token (skipped when the caller already knows)
|
||||
needsLogin := true
|
||||
if !skipLoginCheck {
|
||||
needsLogin, err = authClient.IsLoginRequired(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check login requirement: %v", err)
|
||||
}
|
||||
// check if we need to generate JWT token
|
||||
needsLogin, err := authClient.IsLoginRequired(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check login requirement: %v", err)
|
||||
}
|
||||
|
||||
jwtToken := ""
|
||||
|
||||
@@ -3909,30 +3909,14 @@ func (*SubscribeRequest) Descriptor() ([]byte, []int) {
|
||||
}
|
||||
|
||||
type SystemEvent struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
|
||||
Severity SystemEvent_Severity `protobuf:"varint,2,opt,name=severity,proto3,enum=daemon.SystemEvent_Severity" json:"severity,omitempty"`
|
||||
Category SystemEvent_Category `protobuf:"varint,3,opt,name=category,proto3,enum=daemon.SystemEvent_Category" json:"category,omitempty"`
|
||||
Message string `protobuf:"bytes,4,opt,name=message,proto3" json:"message,omitempty"`
|
||||
// userMessage is the daemon's English rendering of messageKey, kept for the
|
||||
// CLI and for UIs that predate messageKey. UIs that localise read messageKey
|
||||
// and treat this as the fallback.
|
||||
UserMessage string `protobuf:"bytes,5,opt,name=userMessage,proto3" json:"userMessage,omitempty"`
|
||||
Timestamp *timestamppb.Timestamp `protobuf:"bytes,6,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
|
||||
Metadata map[string]string `protobuf:"bytes,7,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
|
||||
// messageKey names a user-facing message in a stable, locale-independent
|
||||
// form. A UI resolves it against its own translation bundle and substitutes
|
||||
// messageArgs; an unrecognised key falls back to userMessage. Empty on events
|
||||
// that carry no user-facing text.
|
||||
MessageKey string `protobuf:"bytes,8,opt,name=messageKey,proto3" json:"messageKey,omitempty"`
|
||||
// messageArgs holds the placeholder name/value pairs for messageKey, e.g.
|
||||
// {"version": "0.60.1"} for a "{version}" template. Values are data the
|
||||
// daemon cannot localise (versions, addresses, error text).
|
||||
MessageArgs map[string]string `protobuf:"bytes,9,rep,name=messageArgs,proto3" json:"messageArgs,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
|
||||
// titleKey names the notification title in the same way as messageKey. Empty
|
||||
// when the event has no dedicated title, in which case a UI composes one from
|
||||
// severity and category.
|
||||
TitleKey string `protobuf:"bytes,10,opt,name=titleKey,proto3" json:"titleKey,omitempty"`
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
|
||||
Severity SystemEvent_Severity `protobuf:"varint,2,opt,name=severity,proto3,enum=daemon.SystemEvent_Severity" json:"severity,omitempty"`
|
||||
Category SystemEvent_Category `protobuf:"varint,3,opt,name=category,proto3,enum=daemon.SystemEvent_Category" json:"category,omitempty"`
|
||||
Message string `protobuf:"bytes,4,opt,name=message,proto3" json:"message,omitempty"`
|
||||
UserMessage string `protobuf:"bytes,5,opt,name=userMessage,proto3" json:"userMessage,omitempty"`
|
||||
Timestamp *timestamppb.Timestamp `protobuf:"bytes,6,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
|
||||
Metadata map[string]string `protobuf:"bytes,7,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -4016,27 +4000,6 @@ func (x *SystemEvent) GetMetadata() map[string]string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *SystemEvent) GetMessageKey() string {
|
||||
if x != nil {
|
||||
return x.MessageKey
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *SystemEvent) GetMessageArgs() map[string]string {
|
||||
if x != nil {
|
||||
return x.MessageArgs
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *SystemEvent) GetTitleKey() string {
|
||||
if x != nil {
|
||||
return x.TitleKey
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type GetEventsRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
@@ -7369,7 +7332,7 @@ const file_daemon_proto_rawDesc = "" +
|
||||
"\x13TracePacketResponse\x12*\n" +
|
||||
"\x06stages\x18\x01 \x03(\v2\x12.daemon.TraceStageR\x06stages\x12+\n" +
|
||||
"\x11final_disposition\x18\x02 \x01(\bR\x10finalDisposition\"\x12\n" +
|
||||
"\x10SubscribeRequest\"\xd7\x05\n" +
|
||||
"\x10SubscribeRequest\"\x93\x04\n" +
|
||||
"\vSystemEvent\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\tR\x02id\x128\n" +
|
||||
"\bseverity\x18\x02 \x01(\x0e2\x1c.daemon.SystemEvent.SeverityR\bseverity\x128\n" +
|
||||
@@ -7377,18 +7340,9 @@ const file_daemon_proto_rawDesc = "" +
|
||||
"\amessage\x18\x04 \x01(\tR\amessage\x12 \n" +
|
||||
"\vuserMessage\x18\x05 \x01(\tR\vuserMessage\x128\n" +
|
||||
"\ttimestamp\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\ttimestamp\x12=\n" +
|
||||
"\bmetadata\x18\a \x03(\v2!.daemon.SystemEvent.MetadataEntryR\bmetadata\x12\x1e\n" +
|
||||
"\n" +
|
||||
"messageKey\x18\b \x01(\tR\n" +
|
||||
"messageKey\x12F\n" +
|
||||
"\vmessageArgs\x18\t \x03(\v2$.daemon.SystemEvent.MessageArgsEntryR\vmessageArgs\x12\x1a\n" +
|
||||
"\btitleKey\x18\n" +
|
||||
" \x01(\tR\btitleKey\x1a;\n" +
|
||||
"\bmetadata\x18\a \x03(\v2!.daemon.SystemEvent.MetadataEntryR\bmetadata\x1a;\n" +
|
||||
"\rMetadataEntry\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
||||
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1a>\n" +
|
||||
"\x10MessageArgsEntry\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
||||
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\":\n" +
|
||||
"\bSeverity\x12\b\n" +
|
||||
"\x04INFO\x10\x00\x12\v\n" +
|
||||
@@ -7706,7 +7660,7 @@ func file_daemon_proto_rawDescGZIP() []byte {
|
||||
}
|
||||
|
||||
var file_daemon_proto_enumTypes = make([]protoimpl.EnumInfo, 4)
|
||||
var file_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 111)
|
||||
var file_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 110)
|
||||
var file_daemon_proto_goTypes = []any{
|
||||
(LogLevel)(0), // 0: daemon.LogLevel
|
||||
(ExposeProtocol)(0), // 1: daemon.ExposeProtocol
|
||||
@@ -7822,17 +7776,16 @@ var file_daemon_proto_goTypes = []any{
|
||||
nil, // 111: daemon.Network.ResolvedIPsEntry
|
||||
(*PortInfo_Range)(nil), // 112: daemon.PortInfo.Range
|
||||
nil, // 113: daemon.SystemEvent.MetadataEntry
|
||||
nil, // 114: daemon.SystemEvent.MessageArgsEntry
|
||||
(*durationpb.Duration)(nil), // 115: google.protobuf.Duration
|
||||
(*timestamppb.Timestamp)(nil), // 116: google.protobuf.Timestamp
|
||||
(*durationpb.Duration)(nil), // 114: google.protobuf.Duration
|
||||
(*timestamppb.Timestamp)(nil), // 115: google.protobuf.Timestamp
|
||||
}
|
||||
var file_daemon_proto_depIdxs = []int32{
|
||||
115, // 0: daemon.LoginRequest.dnsRouteInterval:type_name -> google.protobuf.Duration
|
||||
114, // 0: daemon.LoginRequest.dnsRouteInterval:type_name -> google.protobuf.Duration
|
||||
25, // 1: daemon.StatusResponse.fullStatus:type_name -> daemon.FullStatus
|
||||
116, // 2: daemon.StatusResponse.sessionExpiresAt:type_name -> google.protobuf.Timestamp
|
||||
116, // 3: daemon.PeerState.connStatusUpdate:type_name -> google.protobuf.Timestamp
|
||||
116, // 4: daemon.PeerState.lastWireguardHandshake:type_name -> google.protobuf.Timestamp
|
||||
115, // 5: daemon.PeerState.latency:type_name -> google.protobuf.Duration
|
||||
115, // 2: daemon.StatusResponse.sessionExpiresAt:type_name -> google.protobuf.Timestamp
|
||||
115, // 3: daemon.PeerState.connStatusUpdate:type_name -> google.protobuf.Timestamp
|
||||
115, // 4: daemon.PeerState.lastWireguardHandshake:type_name -> google.protobuf.Timestamp
|
||||
114, // 5: daemon.PeerState.latency:type_name -> google.protobuf.Duration
|
||||
23, // 6: daemon.SSHServerState.sessions:type_name -> daemon.SSHSessionInfo
|
||||
20, // 7: daemon.FullStatus.managementState:type_name -> daemon.ManagementState
|
||||
19, // 8: daemon.FullStatus.signalState:type_name -> daemon.SignalState
|
||||
@@ -7855,115 +7808,114 @@ var file_daemon_proto_depIdxs = []int32{
|
||||
54, // 25: daemon.TracePacketResponse.stages:type_name -> daemon.TraceStage
|
||||
2, // 26: daemon.SystemEvent.severity:type_name -> daemon.SystemEvent.Severity
|
||||
3, // 27: daemon.SystemEvent.category:type_name -> daemon.SystemEvent.Category
|
||||
116, // 28: daemon.SystemEvent.timestamp:type_name -> google.protobuf.Timestamp
|
||||
115, // 28: daemon.SystemEvent.timestamp:type_name -> google.protobuf.Timestamp
|
||||
113, // 29: daemon.SystemEvent.metadata:type_name -> daemon.SystemEvent.MetadataEntry
|
||||
114, // 30: daemon.SystemEvent.messageArgs:type_name -> daemon.SystemEvent.MessageArgsEntry
|
||||
57, // 31: daemon.GetEventsResponse.events:type_name -> daemon.SystemEvent
|
||||
115, // 32: daemon.SetConfigRequest.dnsRouteInterval:type_name -> google.protobuf.Duration
|
||||
72, // 33: daemon.ListProfilesResponse.profiles:type_name -> daemon.Profile
|
||||
116, // 34: daemon.WaitExtendAuthSessionResponse.sessionExpiresAt:type_name -> google.protobuf.Timestamp
|
||||
1, // 35: daemon.ExposeServiceRequest.protocol:type_name -> daemon.ExposeProtocol
|
||||
104, // 36: daemon.ExposeServiceEvent.ready:type_name -> daemon.ExposeServiceReady
|
||||
115, // 37: daemon.StartCaptureRequest.duration:type_name -> google.protobuf.Duration
|
||||
115, // 38: daemon.StartBundleCaptureRequest.timeout:type_name -> google.protobuf.Duration
|
||||
30, // 39: daemon.Network.ResolvedIPsEntry.value:type_name -> daemon.IPList
|
||||
5, // 40: daemon.DaemonService.Login:input_type -> daemon.LoginRequest
|
||||
7, // 41: daemon.DaemonService.WaitSSOLogin:input_type -> daemon.WaitSSOLoginRequest
|
||||
9, // 42: daemon.DaemonService.Up:input_type -> daemon.UpRequest
|
||||
11, // 43: daemon.DaemonService.Status:input_type -> daemon.StatusRequest
|
||||
11, // 44: daemon.DaemonService.SubscribeStatus:input_type -> daemon.StatusRequest
|
||||
13, // 45: daemon.DaemonService.Down:input_type -> daemon.DownRequest
|
||||
15, // 46: daemon.DaemonService.GetConfig:input_type -> daemon.GetConfigRequest
|
||||
26, // 47: daemon.DaemonService.ListNetworks:input_type -> daemon.ListNetworksRequest
|
||||
28, // 48: daemon.DaemonService.SelectNetworks:input_type -> daemon.SelectNetworksRequest
|
||||
28, // 49: daemon.DaemonService.DeselectNetworks:input_type -> daemon.SelectNetworksRequest
|
||||
4, // 50: daemon.DaemonService.ForwardingRules:input_type -> daemon.EmptyRequest
|
||||
35, // 51: daemon.DaemonService.DebugBundle:input_type -> daemon.DebugBundleRequest
|
||||
37, // 52: daemon.DaemonService.GetLogLevel:input_type -> daemon.GetLogLevelRequest
|
||||
39, // 53: daemon.DaemonService.SetLogLevel:input_type -> daemon.SetLogLevelRequest
|
||||
44, // 54: daemon.DaemonService.ListStates:input_type -> daemon.ListStatesRequest
|
||||
46, // 55: daemon.DaemonService.CleanState:input_type -> daemon.CleanStateRequest
|
||||
48, // 56: daemon.DaemonService.DeleteState:input_type -> daemon.DeleteStateRequest
|
||||
50, // 57: daemon.DaemonService.SetSyncResponsePersistence:input_type -> daemon.SetSyncResponsePersistenceRequest
|
||||
53, // 58: daemon.DaemonService.TracePacket:input_type -> daemon.TracePacketRequest
|
||||
105, // 59: daemon.DaemonService.StartCapture:input_type -> daemon.StartCaptureRequest
|
||||
107, // 60: daemon.DaemonService.StartBundleCapture:input_type -> daemon.StartBundleCaptureRequest
|
||||
109, // 61: daemon.DaemonService.StopBundleCapture:input_type -> daemon.StopBundleCaptureRequest
|
||||
56, // 62: daemon.DaemonService.SubscribeEvents:input_type -> daemon.SubscribeRequest
|
||||
58, // 63: daemon.DaemonService.GetEvents:input_type -> daemon.GetEventsRequest
|
||||
41, // 64: daemon.DaemonService.RegisterUILog:input_type -> daemon.RegisterUILogRequest
|
||||
60, // 65: daemon.DaemonService.SwitchProfile:input_type -> daemon.SwitchProfileRequest
|
||||
62, // 66: daemon.DaemonService.SetConfig:input_type -> daemon.SetConfigRequest
|
||||
64, // 67: daemon.DaemonService.AddProfile:input_type -> daemon.AddProfileRequest
|
||||
66, // 68: daemon.DaemonService.RenameProfile:input_type -> daemon.RenameProfileRequest
|
||||
68, // 69: daemon.DaemonService.RemoveProfile:input_type -> daemon.RemoveProfileRequest
|
||||
70, // 70: daemon.DaemonService.ListProfiles:input_type -> daemon.ListProfilesRequest
|
||||
73, // 71: daemon.DaemonService.GetActiveProfile:input_type -> daemon.GetActiveProfileRequest
|
||||
75, // 72: daemon.DaemonService.Logout:input_type -> daemon.LogoutRequest
|
||||
79, // 73: daemon.DaemonService.GetFeatures:input_type -> daemon.GetFeaturesRequest
|
||||
82, // 74: daemon.DaemonService.TriggerUpdate:input_type -> daemon.TriggerUpdateRequest
|
||||
84, // 75: daemon.DaemonService.GetPeerSSHHostKey:input_type -> daemon.GetPeerSSHHostKeyRequest
|
||||
86, // 76: daemon.DaemonService.RequestJWTAuth:input_type -> daemon.RequestJWTAuthRequest
|
||||
88, // 77: daemon.DaemonService.WaitJWTToken:input_type -> daemon.WaitJWTTokenRequest
|
||||
90, // 78: daemon.DaemonService.RequestExtendAuthSession:input_type -> daemon.RequestExtendAuthSessionRequest
|
||||
92, // 79: daemon.DaemonService.WaitExtendAuthSession:input_type -> daemon.WaitExtendAuthSessionRequest
|
||||
94, // 80: daemon.DaemonService.DismissSessionWarning:input_type -> daemon.DismissSessionWarningRequest
|
||||
96, // 81: daemon.DaemonService.StartCPUProfile:input_type -> daemon.StartCPUProfileRequest
|
||||
98, // 82: daemon.DaemonService.StopCPUProfile:input_type -> daemon.StopCPUProfileRequest
|
||||
100, // 83: daemon.DaemonService.GetInstallerResult:input_type -> daemon.InstallerResultRequest
|
||||
102, // 84: daemon.DaemonService.ExposeService:input_type -> daemon.ExposeServiceRequest
|
||||
77, // 85: daemon.DaemonService.WailsUIReady:input_type -> daemon.WailsUIReadyRequest
|
||||
6, // 86: daemon.DaemonService.Login:output_type -> daemon.LoginResponse
|
||||
8, // 87: daemon.DaemonService.WaitSSOLogin:output_type -> daemon.WaitSSOLoginResponse
|
||||
10, // 88: daemon.DaemonService.Up:output_type -> daemon.UpResponse
|
||||
12, // 89: daemon.DaemonService.Status:output_type -> daemon.StatusResponse
|
||||
12, // 90: daemon.DaemonService.SubscribeStatus:output_type -> daemon.StatusResponse
|
||||
14, // 91: daemon.DaemonService.Down:output_type -> daemon.DownResponse
|
||||
16, // 92: daemon.DaemonService.GetConfig:output_type -> daemon.GetConfigResponse
|
||||
27, // 93: daemon.DaemonService.ListNetworks:output_type -> daemon.ListNetworksResponse
|
||||
29, // 94: daemon.DaemonService.SelectNetworks:output_type -> daemon.SelectNetworksResponse
|
||||
29, // 95: daemon.DaemonService.DeselectNetworks:output_type -> daemon.SelectNetworksResponse
|
||||
34, // 96: daemon.DaemonService.ForwardingRules:output_type -> daemon.ForwardingRulesResponse
|
||||
36, // 97: daemon.DaemonService.DebugBundle:output_type -> daemon.DebugBundleResponse
|
||||
38, // 98: daemon.DaemonService.GetLogLevel:output_type -> daemon.GetLogLevelResponse
|
||||
40, // 99: daemon.DaemonService.SetLogLevel:output_type -> daemon.SetLogLevelResponse
|
||||
45, // 100: daemon.DaemonService.ListStates:output_type -> daemon.ListStatesResponse
|
||||
47, // 101: daemon.DaemonService.CleanState:output_type -> daemon.CleanStateResponse
|
||||
49, // 102: daemon.DaemonService.DeleteState:output_type -> daemon.DeleteStateResponse
|
||||
51, // 103: daemon.DaemonService.SetSyncResponsePersistence:output_type -> daemon.SetSyncResponsePersistenceResponse
|
||||
55, // 104: daemon.DaemonService.TracePacket:output_type -> daemon.TracePacketResponse
|
||||
106, // 105: daemon.DaemonService.StartCapture:output_type -> daemon.CapturePacket
|
||||
108, // 106: daemon.DaemonService.StartBundleCapture:output_type -> daemon.StartBundleCaptureResponse
|
||||
110, // 107: daemon.DaemonService.StopBundleCapture:output_type -> daemon.StopBundleCaptureResponse
|
||||
57, // 108: daemon.DaemonService.SubscribeEvents:output_type -> daemon.SystemEvent
|
||||
59, // 109: daemon.DaemonService.GetEvents:output_type -> daemon.GetEventsResponse
|
||||
42, // 110: daemon.DaemonService.RegisterUILog:output_type -> daemon.RegisterUILogResponse
|
||||
61, // 111: daemon.DaemonService.SwitchProfile:output_type -> daemon.SwitchProfileResponse
|
||||
63, // 112: daemon.DaemonService.SetConfig:output_type -> daemon.SetConfigResponse
|
||||
65, // 113: daemon.DaemonService.AddProfile:output_type -> daemon.AddProfileResponse
|
||||
67, // 114: daemon.DaemonService.RenameProfile:output_type -> daemon.RenameProfileResponse
|
||||
69, // 115: daemon.DaemonService.RemoveProfile:output_type -> daemon.RemoveProfileResponse
|
||||
71, // 116: daemon.DaemonService.ListProfiles:output_type -> daemon.ListProfilesResponse
|
||||
74, // 117: daemon.DaemonService.GetActiveProfile:output_type -> daemon.GetActiveProfileResponse
|
||||
76, // 118: daemon.DaemonService.Logout:output_type -> daemon.LogoutResponse
|
||||
80, // 119: daemon.DaemonService.GetFeatures:output_type -> daemon.GetFeaturesResponse
|
||||
83, // 120: daemon.DaemonService.TriggerUpdate:output_type -> daemon.TriggerUpdateResponse
|
||||
85, // 121: daemon.DaemonService.GetPeerSSHHostKey:output_type -> daemon.GetPeerSSHHostKeyResponse
|
||||
87, // 122: daemon.DaemonService.RequestJWTAuth:output_type -> daemon.RequestJWTAuthResponse
|
||||
89, // 123: daemon.DaemonService.WaitJWTToken:output_type -> daemon.WaitJWTTokenResponse
|
||||
91, // 124: daemon.DaemonService.RequestExtendAuthSession:output_type -> daemon.RequestExtendAuthSessionResponse
|
||||
93, // 125: daemon.DaemonService.WaitExtendAuthSession:output_type -> daemon.WaitExtendAuthSessionResponse
|
||||
95, // 126: daemon.DaemonService.DismissSessionWarning:output_type -> daemon.DismissSessionWarningResponse
|
||||
97, // 127: daemon.DaemonService.StartCPUProfile:output_type -> daemon.StartCPUProfileResponse
|
||||
99, // 128: daemon.DaemonService.StopCPUProfile:output_type -> daemon.StopCPUProfileResponse
|
||||
101, // 129: daemon.DaemonService.GetInstallerResult:output_type -> daemon.InstallerResultResponse
|
||||
103, // 130: daemon.DaemonService.ExposeService:output_type -> daemon.ExposeServiceEvent
|
||||
78, // 131: daemon.DaemonService.WailsUIReady:output_type -> daemon.WailsUIReadyResponse
|
||||
86, // [86:132] is the sub-list for method output_type
|
||||
40, // [40:86] is the sub-list for method input_type
|
||||
40, // [40:40] is the sub-list for extension type_name
|
||||
40, // [40:40] is the sub-list for extension extendee
|
||||
0, // [0:40] is the sub-list for field type_name
|
||||
57, // 30: daemon.GetEventsResponse.events:type_name -> daemon.SystemEvent
|
||||
114, // 31: daemon.SetConfigRequest.dnsRouteInterval:type_name -> google.protobuf.Duration
|
||||
72, // 32: daemon.ListProfilesResponse.profiles:type_name -> daemon.Profile
|
||||
115, // 33: daemon.WaitExtendAuthSessionResponse.sessionExpiresAt:type_name -> google.protobuf.Timestamp
|
||||
1, // 34: daemon.ExposeServiceRequest.protocol:type_name -> daemon.ExposeProtocol
|
||||
104, // 35: daemon.ExposeServiceEvent.ready:type_name -> daemon.ExposeServiceReady
|
||||
114, // 36: daemon.StartCaptureRequest.duration:type_name -> google.protobuf.Duration
|
||||
114, // 37: daemon.StartBundleCaptureRequest.timeout:type_name -> google.protobuf.Duration
|
||||
30, // 38: daemon.Network.ResolvedIPsEntry.value:type_name -> daemon.IPList
|
||||
5, // 39: daemon.DaemonService.Login:input_type -> daemon.LoginRequest
|
||||
7, // 40: daemon.DaemonService.WaitSSOLogin:input_type -> daemon.WaitSSOLoginRequest
|
||||
9, // 41: daemon.DaemonService.Up:input_type -> daemon.UpRequest
|
||||
11, // 42: daemon.DaemonService.Status:input_type -> daemon.StatusRequest
|
||||
11, // 43: daemon.DaemonService.SubscribeStatus:input_type -> daemon.StatusRequest
|
||||
13, // 44: daemon.DaemonService.Down:input_type -> daemon.DownRequest
|
||||
15, // 45: daemon.DaemonService.GetConfig:input_type -> daemon.GetConfigRequest
|
||||
26, // 46: daemon.DaemonService.ListNetworks:input_type -> daemon.ListNetworksRequest
|
||||
28, // 47: daemon.DaemonService.SelectNetworks:input_type -> daemon.SelectNetworksRequest
|
||||
28, // 48: daemon.DaemonService.DeselectNetworks:input_type -> daemon.SelectNetworksRequest
|
||||
4, // 49: daemon.DaemonService.ForwardingRules:input_type -> daemon.EmptyRequest
|
||||
35, // 50: daemon.DaemonService.DebugBundle:input_type -> daemon.DebugBundleRequest
|
||||
37, // 51: daemon.DaemonService.GetLogLevel:input_type -> daemon.GetLogLevelRequest
|
||||
39, // 52: daemon.DaemonService.SetLogLevel:input_type -> daemon.SetLogLevelRequest
|
||||
44, // 53: daemon.DaemonService.ListStates:input_type -> daemon.ListStatesRequest
|
||||
46, // 54: daemon.DaemonService.CleanState:input_type -> daemon.CleanStateRequest
|
||||
48, // 55: daemon.DaemonService.DeleteState:input_type -> daemon.DeleteStateRequest
|
||||
50, // 56: daemon.DaemonService.SetSyncResponsePersistence:input_type -> daemon.SetSyncResponsePersistenceRequest
|
||||
53, // 57: daemon.DaemonService.TracePacket:input_type -> daemon.TracePacketRequest
|
||||
105, // 58: daemon.DaemonService.StartCapture:input_type -> daemon.StartCaptureRequest
|
||||
107, // 59: daemon.DaemonService.StartBundleCapture:input_type -> daemon.StartBundleCaptureRequest
|
||||
109, // 60: daemon.DaemonService.StopBundleCapture:input_type -> daemon.StopBundleCaptureRequest
|
||||
56, // 61: daemon.DaemonService.SubscribeEvents:input_type -> daemon.SubscribeRequest
|
||||
58, // 62: daemon.DaemonService.GetEvents:input_type -> daemon.GetEventsRequest
|
||||
41, // 63: daemon.DaemonService.RegisterUILog:input_type -> daemon.RegisterUILogRequest
|
||||
60, // 64: daemon.DaemonService.SwitchProfile:input_type -> daemon.SwitchProfileRequest
|
||||
62, // 65: daemon.DaemonService.SetConfig:input_type -> daemon.SetConfigRequest
|
||||
64, // 66: daemon.DaemonService.AddProfile:input_type -> daemon.AddProfileRequest
|
||||
66, // 67: daemon.DaemonService.RenameProfile:input_type -> daemon.RenameProfileRequest
|
||||
68, // 68: daemon.DaemonService.RemoveProfile:input_type -> daemon.RemoveProfileRequest
|
||||
70, // 69: daemon.DaemonService.ListProfiles:input_type -> daemon.ListProfilesRequest
|
||||
73, // 70: daemon.DaemonService.GetActiveProfile:input_type -> daemon.GetActiveProfileRequest
|
||||
75, // 71: daemon.DaemonService.Logout:input_type -> daemon.LogoutRequest
|
||||
79, // 72: daemon.DaemonService.GetFeatures:input_type -> daemon.GetFeaturesRequest
|
||||
82, // 73: daemon.DaemonService.TriggerUpdate:input_type -> daemon.TriggerUpdateRequest
|
||||
84, // 74: daemon.DaemonService.GetPeerSSHHostKey:input_type -> daemon.GetPeerSSHHostKeyRequest
|
||||
86, // 75: daemon.DaemonService.RequestJWTAuth:input_type -> daemon.RequestJWTAuthRequest
|
||||
88, // 76: daemon.DaemonService.WaitJWTToken:input_type -> daemon.WaitJWTTokenRequest
|
||||
90, // 77: daemon.DaemonService.RequestExtendAuthSession:input_type -> daemon.RequestExtendAuthSessionRequest
|
||||
92, // 78: daemon.DaemonService.WaitExtendAuthSession:input_type -> daemon.WaitExtendAuthSessionRequest
|
||||
94, // 79: daemon.DaemonService.DismissSessionWarning:input_type -> daemon.DismissSessionWarningRequest
|
||||
96, // 80: daemon.DaemonService.StartCPUProfile:input_type -> daemon.StartCPUProfileRequest
|
||||
98, // 81: daemon.DaemonService.StopCPUProfile:input_type -> daemon.StopCPUProfileRequest
|
||||
100, // 82: daemon.DaemonService.GetInstallerResult:input_type -> daemon.InstallerResultRequest
|
||||
102, // 83: daemon.DaemonService.ExposeService:input_type -> daemon.ExposeServiceRequest
|
||||
77, // 84: daemon.DaemonService.WailsUIReady:input_type -> daemon.WailsUIReadyRequest
|
||||
6, // 85: daemon.DaemonService.Login:output_type -> daemon.LoginResponse
|
||||
8, // 86: daemon.DaemonService.WaitSSOLogin:output_type -> daemon.WaitSSOLoginResponse
|
||||
10, // 87: daemon.DaemonService.Up:output_type -> daemon.UpResponse
|
||||
12, // 88: daemon.DaemonService.Status:output_type -> daemon.StatusResponse
|
||||
12, // 89: daemon.DaemonService.SubscribeStatus:output_type -> daemon.StatusResponse
|
||||
14, // 90: daemon.DaemonService.Down:output_type -> daemon.DownResponse
|
||||
16, // 91: daemon.DaemonService.GetConfig:output_type -> daemon.GetConfigResponse
|
||||
27, // 92: daemon.DaemonService.ListNetworks:output_type -> daemon.ListNetworksResponse
|
||||
29, // 93: daemon.DaemonService.SelectNetworks:output_type -> daemon.SelectNetworksResponse
|
||||
29, // 94: daemon.DaemonService.DeselectNetworks:output_type -> daemon.SelectNetworksResponse
|
||||
34, // 95: daemon.DaemonService.ForwardingRules:output_type -> daemon.ForwardingRulesResponse
|
||||
36, // 96: daemon.DaemonService.DebugBundle:output_type -> daemon.DebugBundleResponse
|
||||
38, // 97: daemon.DaemonService.GetLogLevel:output_type -> daemon.GetLogLevelResponse
|
||||
40, // 98: daemon.DaemonService.SetLogLevel:output_type -> daemon.SetLogLevelResponse
|
||||
45, // 99: daemon.DaemonService.ListStates:output_type -> daemon.ListStatesResponse
|
||||
47, // 100: daemon.DaemonService.CleanState:output_type -> daemon.CleanStateResponse
|
||||
49, // 101: daemon.DaemonService.DeleteState:output_type -> daemon.DeleteStateResponse
|
||||
51, // 102: daemon.DaemonService.SetSyncResponsePersistence:output_type -> daemon.SetSyncResponsePersistenceResponse
|
||||
55, // 103: daemon.DaemonService.TracePacket:output_type -> daemon.TracePacketResponse
|
||||
106, // 104: daemon.DaemonService.StartCapture:output_type -> daemon.CapturePacket
|
||||
108, // 105: daemon.DaemonService.StartBundleCapture:output_type -> daemon.StartBundleCaptureResponse
|
||||
110, // 106: daemon.DaemonService.StopBundleCapture:output_type -> daemon.StopBundleCaptureResponse
|
||||
57, // 107: daemon.DaemonService.SubscribeEvents:output_type -> daemon.SystemEvent
|
||||
59, // 108: daemon.DaemonService.GetEvents:output_type -> daemon.GetEventsResponse
|
||||
42, // 109: daemon.DaemonService.RegisterUILog:output_type -> daemon.RegisterUILogResponse
|
||||
61, // 110: daemon.DaemonService.SwitchProfile:output_type -> daemon.SwitchProfileResponse
|
||||
63, // 111: daemon.DaemonService.SetConfig:output_type -> daemon.SetConfigResponse
|
||||
65, // 112: daemon.DaemonService.AddProfile:output_type -> daemon.AddProfileResponse
|
||||
67, // 113: daemon.DaemonService.RenameProfile:output_type -> daemon.RenameProfileResponse
|
||||
69, // 114: daemon.DaemonService.RemoveProfile:output_type -> daemon.RemoveProfileResponse
|
||||
71, // 115: daemon.DaemonService.ListProfiles:output_type -> daemon.ListProfilesResponse
|
||||
74, // 116: daemon.DaemonService.GetActiveProfile:output_type -> daemon.GetActiveProfileResponse
|
||||
76, // 117: daemon.DaemonService.Logout:output_type -> daemon.LogoutResponse
|
||||
80, // 118: daemon.DaemonService.GetFeatures:output_type -> daemon.GetFeaturesResponse
|
||||
83, // 119: daemon.DaemonService.TriggerUpdate:output_type -> daemon.TriggerUpdateResponse
|
||||
85, // 120: daemon.DaemonService.GetPeerSSHHostKey:output_type -> daemon.GetPeerSSHHostKeyResponse
|
||||
87, // 121: daemon.DaemonService.RequestJWTAuth:output_type -> daemon.RequestJWTAuthResponse
|
||||
89, // 122: daemon.DaemonService.WaitJWTToken:output_type -> daemon.WaitJWTTokenResponse
|
||||
91, // 123: daemon.DaemonService.RequestExtendAuthSession:output_type -> daemon.RequestExtendAuthSessionResponse
|
||||
93, // 124: daemon.DaemonService.WaitExtendAuthSession:output_type -> daemon.WaitExtendAuthSessionResponse
|
||||
95, // 125: daemon.DaemonService.DismissSessionWarning:output_type -> daemon.DismissSessionWarningResponse
|
||||
97, // 126: daemon.DaemonService.StartCPUProfile:output_type -> daemon.StartCPUProfileResponse
|
||||
99, // 127: daemon.DaemonService.StopCPUProfile:output_type -> daemon.StopCPUProfileResponse
|
||||
101, // 128: daemon.DaemonService.GetInstallerResult:output_type -> daemon.InstallerResultResponse
|
||||
103, // 129: daemon.DaemonService.ExposeService:output_type -> daemon.ExposeServiceEvent
|
||||
78, // 130: daemon.DaemonService.WailsUIReady:output_type -> daemon.WailsUIReadyResponse
|
||||
85, // [85:131] is the sub-list for method output_type
|
||||
39, // [39:85] is the sub-list for method input_type
|
||||
39, // [39:39] is the sub-list for extension type_name
|
||||
39, // [39:39] is the sub-list for extension extendee
|
||||
0, // [0:39] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_daemon_proto_init() }
|
||||
@@ -7995,7 +7947,7 @@ func file_daemon_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_daemon_proto_rawDesc), len(file_daemon_proto_rawDesc)),
|
||||
NumEnums: 4,
|
||||
NumMessages: 111,
|
||||
NumMessages: 110,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
|
||||
@@ -677,25 +677,9 @@ message SystemEvent {
|
||||
Severity severity = 2;
|
||||
Category category = 3;
|
||||
string message = 4;
|
||||
// userMessage is the daemon's English rendering of messageKey, kept for the
|
||||
// CLI and for UIs that predate messageKey. UIs that localise read messageKey
|
||||
// and treat this as the fallback.
|
||||
string userMessage = 5;
|
||||
google.protobuf.Timestamp timestamp = 6;
|
||||
map<string, string> metadata = 7;
|
||||
// messageKey names a user-facing message in a stable, locale-independent
|
||||
// form. A UI resolves it against its own translation bundle and substitutes
|
||||
// messageArgs; an unrecognised key falls back to userMessage. Empty on events
|
||||
// that carry no user-facing text.
|
||||
string messageKey = 8;
|
||||
// messageArgs holds the placeholder name/value pairs for messageKey, e.g.
|
||||
// {"version": "0.60.1"} for a "{version}" template. Values are data the
|
||||
// daemon cannot localise (versions, addresses, error text).
|
||||
map<string, string> messageArgs = 9;
|
||||
// titleKey names the notification title in the same way as messageKey. Empty
|
||||
// when the event has no dedicated title, in which case a UI composes one from
|
||||
// severity and category.
|
||||
string titleKey = 10;
|
||||
}
|
||||
|
||||
message GetEventsRequest {}
|
||||
|
||||
@@ -43,10 +43,10 @@ const (
|
||||
// UIs to re-fetch their cached config + features. UserMessage is empty so
|
||||
// the change is silent; the source is carried in MetadataSourceKey.
|
||||
MetadataTypeConfigChanged = "config_changed"
|
||||
// MetadataTypePolicyApplied marks an MDM-policy-driven config change. It is
|
||||
// the user-facing half of the pair: the daemon stamps it with the message
|
||||
// and title keys a UI localises, while the paired config_changed event stays
|
||||
// silent and only drives the cache refresh.
|
||||
// MetadataTypePolicyApplied marks an MDM-policy-driven config change. The
|
||||
// daemon stamps it with a (non-localised) UserMessage; the UI suppresses
|
||||
// that and builds its own localised toast off the paired config_changed
|
||||
// event instead.
|
||||
MetadataTypePolicyApplied = "policy_applied"
|
||||
|
||||
// MetadataSourceKey is the SystemEvent.metadata key carrying what
|
||||
|
||||
@@ -1,183 +0,0 @@
|
||||
package proto
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// UserMessageKey names a piece of user-facing SystemEvent text in a
|
||||
// locale-independent form. The daemon has no notion of the user's language, so it
|
||||
// publishes the key and lets each UI resolve it.
|
||||
//
|
||||
// The value doubles as the lookup key in the desktop UI's translation bundles
|
||||
// (client/ui/i18n/locales/<code>/common.json), so renaming a constant here means
|
||||
// renaming the key in every bundle. The tests in client/ui/i18n lock the two
|
||||
// sides together. Keys that predate this mechanism keep their original bundle
|
||||
// names so the shipped translations still apply.
|
||||
type UserMessageKey string
|
||||
|
||||
// Message-body keys published by the daemon. Every key needs an entry in
|
||||
// UserMessageTexts below and a translation in the UI bundles.
|
||||
const (
|
||||
// UserMsgPanic is the CRITICAL event published from the recover() guard in
|
||||
// the connect loop.
|
||||
UserMsgPanic UserMessageKey = "event.panic"
|
||||
|
||||
// UserMsgDNSRecovered and UserMsgDNSUnreachable bracket a nameserver
|
||||
// group's health transitions.
|
||||
UserMsgDNSRecovered UserMessageKey = "event.dns.recovered"
|
||||
UserMsgDNSUnreachable UserMessageKey = "event.dns.unreachable"
|
||||
|
||||
// Exit-node (default route) transitions.
|
||||
UserMsgExitNodeConnected UserMessageKey = "event.exitNode.connected"
|
||||
UserMsgExitNodeDisconnected UserMessageKey = "event.exitNode.disconnected"
|
||||
UserMsgExitNodeConnectionLost UserMessageKey = "event.exitNode.connectionLost"
|
||||
UserMsgExitNodeHAChange UserMessageKey = "event.exitNode.haChange"
|
||||
UserMsgExitNodeDisconnectedUnknown UserMessageKey = "event.exitNode.disconnectedUnknown"
|
||||
|
||||
// Auto-update lifecycle. UserMsgUpdateFailed takes a {reason} argument and
|
||||
// UserMsgUpdateCompleted a {version}.
|
||||
UserMsgUpdateInstalling UserMessageKey = "event.update.installing"
|
||||
UserMsgUpdateCompleted UserMessageKey = "event.update.completed"
|
||||
UserMsgUpdateFailed UserMessageKey = "event.update.failed"
|
||||
|
||||
// UserMsgMDMPolicyApplied reports that an MDM policy replaced the config.
|
||||
UserMsgMDMPolicyApplied UserMessageKey = "notify.mdm.policyApplied.body"
|
||||
|
||||
// Session-expiry events. UserMsgSessionExpiresIn takes a {remaining}
|
||||
// argument; the "soon" variant is published when the deadline has already
|
||||
// passed by the time the warning fires.
|
||||
UserMsgSessionExpiresIn UserMessageKey = "notify.sessionWarning.body"
|
||||
UserMsgSessionExpiresSoon UserMessageKey = "notify.sessionWarning.bodyGeneric"
|
||||
UserMsgSessionDeadlineReject UserMessageKey = "notify.sessionDeadlineRejected.body"
|
||||
)
|
||||
|
||||
// Notification-title keys. An event without one leaves titleKey empty and the UI
|
||||
// composes a title from severity and category, which is what every event did
|
||||
// before message keys existed. These carry no English fallback: a UI old enough
|
||||
// to ignore titleKey already builds its own title.
|
||||
const (
|
||||
TitleMDMPolicyApplied UserMessageKey = "notify.mdm.policyApplied.title"
|
||||
TitleSessionWarning UserMessageKey = "notify.sessionWarning.title"
|
||||
TitleSessionDeadlineReject UserMessageKey = "notify.sessionDeadlineRejected.title"
|
||||
)
|
||||
|
||||
// UserMessageTitleKeys lists every title key a daemon can publish. It sits next
|
||||
// to the constants above because the two must grow together: a title key missing
|
||||
// from this slice ships untranslated, and the i18n test that would have caught it
|
||||
// reads this list.
|
||||
var UserMessageTitleKeys = []UserMessageKey{
|
||||
TitleMDMPolicyApplied,
|
||||
TitleSessionWarning,
|
||||
TitleSessionDeadlineReject,
|
||||
}
|
||||
|
||||
// ArgReason, ArgVersion and ArgRemaining are the placeholder names used by the
|
||||
// templates below. Producers pass them to NewUserMessage; the UI bundles use the
|
||||
// same names inside {}.
|
||||
const (
|
||||
ArgReason = "reason"
|
||||
ArgVersion = "version"
|
||||
ArgRemaining = "remaining"
|
||||
)
|
||||
|
||||
// UserMessageTexts is the English rendering of every body key, and the source of
|
||||
// the SystemEvent.userMessage fallback that the CLI and pre-messageKey UIs read.
|
||||
// It must match the en bundle, which the i18n test enforces.
|
||||
var UserMessageTexts = map[UserMessageKey]string{
|
||||
UserMsgPanic: "The NetBird service panicked. Please restart the service and submit a bug report with the client logs.",
|
||||
UserMsgDNSRecovered: "DNS servers are reachable again.",
|
||||
UserMsgDNSUnreachable: "Unable to reach one or more DNS servers. This might affect your ability to connect to some services.",
|
||||
UserMsgExitNodeConnected: "Exit node connected.",
|
||||
UserMsgExitNodeDisconnected: "Exit node disconnected.",
|
||||
UserMsgExitNodeConnectionLost: "Exit node connection lost. Your internet access might be affected.",
|
||||
UserMsgExitNodeHAChange: "Exit node disconnected due to high availability change.",
|
||||
UserMsgExitNodeDisconnectedUnknown: "Exit node disconnected for unknown reasons.",
|
||||
UserMsgUpdateInstalling: "Installing update now.",
|
||||
UserMsgUpdateCompleted: "Your NetBird client was auto-updated to version {version}.",
|
||||
UserMsgUpdateFailed: "Auto-update failed: {reason}",
|
||||
UserMsgMDMPolicyApplied: "Your NetBird configuration was updated by your IT policy.",
|
||||
UserMsgSessionExpiresIn: "Your NetBird session expires in {remaining}. Click Extend now to renew.",
|
||||
UserMsgSessionExpiresSoon: "Your NetBird session is about to expire. Click Extend now to renew.",
|
||||
UserMsgSessionDeadlineReject: "The server sent an invalid session deadline. Please sign in again.",
|
||||
}
|
||||
|
||||
// UserMessage is a localizable user-facing event message: a stable body key, an
|
||||
// optional title key, and the placeholder values to substitute. A nil
|
||||
// *UserMessage carries no user-facing text, which is how internal control events
|
||||
// are published.
|
||||
type UserMessage struct {
|
||||
key UserMessageKey
|
||||
title UserMessageKey
|
||||
args map[string]string
|
||||
}
|
||||
|
||||
// NewUserMessage builds a UserMessage from key and flat placeholder name/value
|
||||
// pairs, e.g. NewUserMessage(UserMsgUpdateCompleted, ArgVersion, "0.60.1"). An
|
||||
// unpaired trailing argument is dropped.
|
||||
func NewUserMessage(key UserMessageKey, args ...string) *UserMessage {
|
||||
m := &UserMessage{key: key}
|
||||
if len(args)%2 != 0 {
|
||||
log.Debugf("user message %q: placeholder args not paired: %d items, last dropped", key, len(args))
|
||||
args = args[:len(args)-1]
|
||||
}
|
||||
if len(args) > 0 {
|
||||
m.args = make(map[string]string, len(args)/2)
|
||||
for i := 0; i < len(args); i += 2 {
|
||||
m.args[args[i]] = args[i+1]
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// WithTitle attaches a notification title key and returns m, so it chains onto
|
||||
// NewUserMessage.
|
||||
func (m *UserMessage) WithTitle(key UserMessageKey) *UserMessage {
|
||||
m.title = key
|
||||
return m
|
||||
}
|
||||
|
||||
// Key returns the body key, or the empty key for a nil message.
|
||||
func (m *UserMessage) Key() UserMessageKey {
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
return m.key
|
||||
}
|
||||
|
||||
// TitleKey returns the title key, which is empty unless WithTitle was called.
|
||||
func (m *UserMessage) TitleKey() UserMessageKey {
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
return m.title
|
||||
}
|
||||
|
||||
// Args returns the placeholder values, or nil for a nil message. The map is the
|
||||
// message's own and must not be mutated by the caller; it is handed straight to
|
||||
// SystemEvent.messageArgs.
|
||||
func (m *UserMessage) Args() map[string]string {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
return m.args
|
||||
}
|
||||
|
||||
// Text renders the English fallback for m, with placeholders substituted. A nil
|
||||
// message, or a key with no registered template, renders empty so a UI treats
|
||||
// the event as carrying no user-facing text.
|
||||
func (m *UserMessage) Text() string {
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
tmpl, ok := UserMessageTexts[m.key]
|
||||
if !ok {
|
||||
log.Warnf("no English template for user message key %q", m.key)
|
||||
return ""
|
||||
}
|
||||
for name, value := range m.args {
|
||||
tmpl = strings.ReplaceAll(tmpl, "{"+name+"}", value)
|
||||
}
|
||||
return tmpl
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package proto
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestUserMessageText(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
msg *UserMessage
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "no placeholders",
|
||||
msg: NewUserMessage(UserMsgExitNodeConnected),
|
||||
want: "Exit node connected.",
|
||||
},
|
||||
{
|
||||
name: "placeholder substituted",
|
||||
msg: NewUserMessage(UserMsgUpdateCompleted, ArgVersion, "0.60.1"),
|
||||
want: "Your NetBird client was auto-updated to version 0.60.1.",
|
||||
},
|
||||
{
|
||||
// A dangling arg is a caller mistake; dropping it must still yield a
|
||||
// readable sentence rather than panicking on the wire path.
|
||||
name: "unpaired trailing arg dropped",
|
||||
msg: NewUserMessage(UserMsgUpdateFailed, ArgReason, "disk full", "extra"),
|
||||
want: "Auto-update failed: disk full",
|
||||
},
|
||||
{
|
||||
name: "unknown key renders empty so the UI treats the event as silent",
|
||||
msg: NewUserMessage("event.notRegistered"),
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "nil message carries no text",
|
||||
msg: nil,
|
||||
want: "",
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert.Equal(t, tc.want, tc.msg.Text())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A nil *UserMessage is how every internal control event is published, so the
|
||||
// accessors must stay usable without a nil check at each of the ~25 call sites.
|
||||
func TestNilUserMessageAccessors(t *testing.T) {
|
||||
var msg *UserMessage
|
||||
|
||||
assert.Empty(t, msg.Key(), "nil message must have no body key")
|
||||
assert.Empty(t, msg.TitleKey(), "nil message must have no title key")
|
||||
assert.Nil(t, msg.Args(), "nil message must have no args")
|
||||
assert.Empty(t, msg.Text(), "nil message must render empty")
|
||||
}
|
||||
|
||||
func TestUserMessageArgsAndTitle(t *testing.T) {
|
||||
msg := NewUserMessage(UserMsgSessionExpiresIn, ArgRemaining, "10m").
|
||||
WithTitle(TitleSessionWarning)
|
||||
|
||||
assert.Equal(t, UserMsgSessionExpiresIn, msg.Key())
|
||||
assert.Equal(t, TitleSessionWarning, msg.TitleKey())
|
||||
assert.Equal(t, map[string]string{ArgRemaining: "10m"}, msg.Args())
|
||||
assert.Equal(t, "Your NetBird session expires in 10m. Click Extend now to renew.", msg.Text())
|
||||
}
|
||||
|
||||
// Every registered template must be reachable: a key whose text is empty would
|
||||
// publish an event with a key but no fallback for the CLI and older UIs.
|
||||
func TestUserMessageTextsAreNonEmpty(t *testing.T) {
|
||||
texts := UserMessageTexts
|
||||
assert.NotEmpty(t, texts, "the catalog must not be empty")
|
||||
|
||||
for key, text := range texts {
|
||||
assert.NotEmpty(t, text, "message key %q has an empty template", key)
|
||||
assert.NotEmpty(t, key, "the catalog must not contain an empty key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserMessageTitleKeysAreUnique(t *testing.T) {
|
||||
seen := make(map[UserMessageKey]struct{})
|
||||
for _, key := range UserMessageTitleKeys {
|
||||
assert.NotEmpty(t, key, "title keys must not be empty")
|
||||
_, dup := seen[key]
|
||||
assert.False(t, dup, "title key %q listed twice", key)
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
}
|
||||
@@ -94,12 +94,12 @@ func (s *Server) onMDMPolicyChange(_, _ *mdm.Policy) error {
|
||||
// publishConfigChangedEvent has already fired inside
|
||||
// restartEngineForMDMLocked with source="mdm". Emit an MDM-specific
|
||||
// user-visible toast so the operator knows their IT policy was
|
||||
// applied; the message and title keys let the GUI localise it.
|
||||
// applied (UserMessage != "" triggers the GUI notifier).
|
||||
s.statusRecorder.PublishEvent(
|
||||
proto.SystemEvent_INFO,
|
||||
proto.SystemEvent_SYSTEM,
|
||||
"MDM policy applied",
|
||||
proto.NewUserMessage(proto.UserMsgMDMPolicyApplied).WithTitle(proto.TitleMDMPolicyApplied),
|
||||
"NetBird configuration was updated by your IT policy.",
|
||||
map[string]string{
|
||||
proto.MetadataSourceKey: proto.MetadataSourceMDM,
|
||||
proto.MetadataTypeKey: proto.MetadataTypePolicyApplied,
|
||||
@@ -126,7 +126,7 @@ func (s *Server) publishConfigChangedEvent(source string) {
|
||||
proto.SystemEvent_INFO,
|
||||
proto.SystemEvent_SYSTEM,
|
||||
fmt.Sprintf("daemon config changed (source=%s)", source),
|
||||
nil,
|
||||
"",
|
||||
map[string]string{
|
||||
proto.MetadataSourceKey: source,
|
||||
proto.MetadataTypeKey: proto.MetadataTypeConfigChanged,
|
||||
|
||||
@@ -170,7 +170,7 @@ func (s *Server) SelectNetworks(_ context.Context, req *proto.SelectNetworksRequ
|
||||
proto.SystemEvent_INFO,
|
||||
proto.SystemEvent_SYSTEM,
|
||||
"Network selection changed",
|
||||
nil,
|
||||
"",
|
||||
map[string]string{
|
||||
"networks": strings.Join(req.GetNetworkIDs(), ", "),
|
||||
"append": fmt.Sprint(req.GetAppend()),
|
||||
@@ -214,7 +214,7 @@ func (s *Server) DeselectNetworks(_ context.Context, req *proto.SelectNetworksRe
|
||||
proto.SystemEvent_INFO,
|
||||
proto.SystemEvent_SYSTEM,
|
||||
"Network deselection changed",
|
||||
nil,
|
||||
"",
|
||||
map[string]string{
|
||||
"networks": strings.Join(req.GetNetworkIDs(), ", "),
|
||||
"append": fmt.Sprint(req.GetAppend()),
|
||||
@@ -232,3 +232,4 @@ func toNetIDs(routes []string) []route.NetID {
|
||||
}
|
||||
return netIDs
|
||||
}
|
||||
|
||||
|
||||
@@ -2181,7 +2181,7 @@ func (s *Server) publishProfileListChanged(profileName string) {
|
||||
proto.SystemEvent_INFO,
|
||||
proto.SystemEvent_SYSTEM,
|
||||
"Profile list changed",
|
||||
nil,
|
||||
"",
|
||||
map[string]string{proto.MetadataKindKey: proto.MetadataKindProfileListChanged, proto.MetadataProfileKey: profileName},
|
||||
)
|
||||
}
|
||||
@@ -2200,7 +2200,7 @@ func (s *Server) publishLogLevelChanged(level string) {
|
||||
proto.SystemEvent_INFO,
|
||||
proto.SystemEvent_SYSTEM,
|
||||
"Log level changed",
|
||||
nil,
|
||||
"",
|
||||
map[string]string{proto.MetadataKindKey: proto.MetadataKindLogLevelChanged, proto.MetadataLevelKey: level},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -40,12 +40,6 @@ i18n/locales/<code>/common.json a target — message only
|
||||
|
||||
Chrome-extension JSON, each key → `{ "message", "description" }`. You translate the **`message`**.
|
||||
|
||||
The `event.*` keys are a special group: the background service names them when it
|
||||
publishes a notification, and the app looks them up here. Their names are part of
|
||||
a Go↔JSON contract (`client/proto/usermsg.go`), so they are even less renameable
|
||||
than the rest — and a missing one shows the user English. Tests fail the build if
|
||||
any locale drops one.
|
||||
|
||||
| ✅ Do | ❌ Don't |
|
||||
|---|---|
|
||||
| Keep **every key** from `en`, in the same order | Translate, rename, reorder, drop, or add keys (they're identifiers; the set grows over time) |
|
||||
|
||||
@@ -126,29 +126,18 @@ func (b *Bundle) BundleFor(code LanguageCode) (map[string]string, error) {
|
||||
// pairs ("version", "1.2.3" replaces "{version}"). Unknown keys fall back to
|
||||
// the default language, then to the key itself so a miss is visible in the UI.
|
||||
func (b *Bundle) Translate(lang LanguageCode, key string, args ...string) string {
|
||||
if v, ok := b.Lookup(lang, key, args...); ok {
|
||||
return v
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
// Lookup resolves key like Translate but reports whether it was found in the
|
||||
// requested or the default bundle. Callers holding a better fallback than the
|
||||
// raw key — a daemon-supplied English string for a key this build predates —
|
||||
// use this to tell a miss from a hit.
|
||||
func (b *Bundle) Lookup(lang LanguageCode, key string, args ...string) (string, bool) {
|
||||
b.mu.RLock()
|
||||
defer b.mu.RUnlock()
|
||||
|
||||
if v, ok := b.bundles[lang][key]; ok {
|
||||
return applyPlaceholders(v, args), true
|
||||
return applyPlaceholders(v, args)
|
||||
}
|
||||
if lang != DefaultLanguage {
|
||||
if v, ok := b.bundles[DefaultLanguage][key]; ok {
|
||||
return applyPlaceholders(v, args), true
|
||||
return applyPlaceholders(v, args)
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
return key
|
||||
}
|
||||
|
||||
// applyPlaceholders substitutes {name} in s using args as flat name/value
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
//go:build !android && !ios && !freebsd && !js
|
||||
|
||||
package i18n
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/netbirdio/netbird/client/proto"
|
||||
)
|
||||
|
||||
// shippedBundle loads the real locale tree rather than the fstest fixture the
|
||||
// other tests use: these checks exist to catch a key the daemon publishes but no
|
||||
// bundle translates, which only the shipped files can prove.
|
||||
func shippedBundle(t *testing.T) *Bundle {
|
||||
t.Helper()
|
||||
b, err := NewBundle(os.DirFS("locales"))
|
||||
require.NoError(t, err, "the shipped locale tree must load")
|
||||
return b
|
||||
}
|
||||
|
||||
// The daemon publishes a message key and each UI resolves it locally, so a key
|
||||
// with no en entry degrades to the daemon's English fallback and silently stops
|
||||
// being translatable. Fail the build instead.
|
||||
func TestUserMessageKeysExistInEnglishBundle(t *testing.T) {
|
||||
b := shippedBundle(t)
|
||||
|
||||
for key, text := range proto.UserMessageTexts {
|
||||
got, ok := b.Lookup(DefaultLanguage, string(key))
|
||||
if !assert.True(t, ok, "message key %q has no en translation", key) {
|
||||
continue
|
||||
}
|
||||
assert.Equal(t, text, got,
|
||||
"en translation of %q must match the daemon's English fallback", key)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserMessageTitleKeysExistInEnglishBundle(t *testing.T) {
|
||||
b := shippedBundle(t)
|
||||
|
||||
for _, key := range proto.UserMessageTitleKeys {
|
||||
_, ok := b.Lookup(DefaultLanguage, string(key))
|
||||
assert.True(t, ok, "title key %q has no en translation", key)
|
||||
}
|
||||
}
|
||||
|
||||
// Every shipped locale must translate the daemon's keys, not just en. A missing
|
||||
// one still renders (Lookup falls back to en) but the notification would show up
|
||||
// in English for that user, which is the bug this whole mechanism exists to fix.
|
||||
func TestUserMessageKeysTranslatedInEveryLanguage(t *testing.T) {
|
||||
b := shippedBundle(t)
|
||||
|
||||
keys := make([]proto.UserMessageKey, 0, len(proto.UserMessageTexts))
|
||||
for key := range proto.UserMessageTexts {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
keys = append(keys, proto.UserMessageTitleKeys...)
|
||||
|
||||
for _, lang := range b.Languages() {
|
||||
bundle, err := b.BundleFor(lang.Code)
|
||||
require.NoError(t, err, "BundleFor(%q)", lang.Code)
|
||||
|
||||
for _, key := range keys {
|
||||
text, ok := bundle[string(key)]
|
||||
if !assert.True(t, ok, "locale %q is missing key %q", lang.Code, key) {
|
||||
continue
|
||||
}
|
||||
assert.NotEmpty(t, text, "locale %q has an empty message for %q", lang.Code, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The tray composes a title from these when an event carries no title key, so a
|
||||
// gap here would render "event.severity.warning: DNS" to the user.
|
||||
func TestEventTitleKeysTranslatedInEveryLanguage(t *testing.T) {
|
||||
b := shippedBundle(t)
|
||||
|
||||
keys := []string{
|
||||
"event.title",
|
||||
"event.severity.info", "event.severity.warning",
|
||||
"event.severity.error", "event.severity.critical",
|
||||
"event.category.network", "event.category.dns",
|
||||
"event.category.authentication", "event.category.connectivity",
|
||||
"event.category.system",
|
||||
}
|
||||
|
||||
for _, lang := range b.Languages() {
|
||||
bundle, err := b.BundleFor(lang.Code)
|
||||
require.NoError(t, err, "BundleFor(%q)", lang.Code)
|
||||
|
||||
for _, key := range keys {
|
||||
text, ok := bundle[key]
|
||||
if !assert.True(t, ok, "locale %q is missing key %q", lang.Code, key) {
|
||||
continue
|
||||
}
|
||||
assert.NotEmpty(t, text, "locale %q has an empty message for %q", lang.Code, key)
|
||||
}
|
||||
}
|
||||
|
||||
// The composed title is useless without both slots.
|
||||
title, ok := b.Lookup(DefaultLanguage, "event.title", "severity", "Warning", "category", "DNS")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "Warning: DNS", title, "event.title must substitute both placeholders")
|
||||
}
|
||||
|
||||
func TestBundleLookupReportsMisses(t *testing.T) {
|
||||
b, err := NewBundle(fakeLocales())
|
||||
require.NoError(t, err)
|
||||
|
||||
got, ok := b.Lookup("en", "tray.menu.connect")
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, "Connect", got)
|
||||
|
||||
// An absent key must report a miss rather than echo the key, so callers can
|
||||
// substitute their own fallback.
|
||||
got, ok = b.Lookup("en", "tray.missing")
|
||||
assert.False(t, ok, "unknown key must report a miss")
|
||||
assert.Empty(t, got, "a miss must not return the key")
|
||||
|
||||
// Empty keys reach Lookup from events that carry no title key at all.
|
||||
_, ok = b.Lookup("en", "")
|
||||
assert.False(t, ok, "empty key must report a miss")
|
||||
}
|
||||
@@ -179,69 +179,6 @@
|
||||
"notify.mdm.policyApplied.body": {
|
||||
"message": "Ihre NetBird-Konfiguration wurde durch Ihre IT-Richtlinie aktualisiert."
|
||||
},
|
||||
"event.title": {
|
||||
"message": "{severity}: {category}"
|
||||
},
|
||||
"event.severity.info": {
|
||||
"message": "Info"
|
||||
},
|
||||
"event.severity.warning": {
|
||||
"message": "Warnung"
|
||||
},
|
||||
"event.severity.error": {
|
||||
"message": "Fehler"
|
||||
},
|
||||
"event.severity.critical": {
|
||||
"message": "Kritisch"
|
||||
},
|
||||
"event.category.network": {
|
||||
"message": "Netzwerk"
|
||||
},
|
||||
"event.category.dns": {
|
||||
"message": "DNS"
|
||||
},
|
||||
"event.category.authentication": {
|
||||
"message": "Authentifizierung"
|
||||
},
|
||||
"event.category.connectivity": {
|
||||
"message": "Konnektivität"
|
||||
},
|
||||
"event.category.system": {
|
||||
"message": "System"
|
||||
},
|
||||
"event.panic": {
|
||||
"message": "Der NetBird-Dienst ist abgestürzt. Bitte starten Sie den Dienst neu und senden Sie einen Fehlerbericht mit den Client-Protokollen."
|
||||
},
|
||||
"event.dns.recovered": {
|
||||
"message": "DNS-Server sind wieder erreichbar."
|
||||
},
|
||||
"event.dns.unreachable": {
|
||||
"message": "Ein oder mehrere DNS-Server sind nicht erreichbar. Das kann die Verbindung zu einigen Diensten beeinträchtigen."
|
||||
},
|
||||
"event.exitNode.connected": {
|
||||
"message": "Exit Node verbunden."
|
||||
},
|
||||
"event.exitNode.disconnected": {
|
||||
"message": "Exit Node getrennt."
|
||||
},
|
||||
"event.exitNode.connectionLost": {
|
||||
"message": "Verbindung zum Exit Node verloren. Ihr Internetzugang kann beeinträchtigt sein."
|
||||
},
|
||||
"event.exitNode.haChange": {
|
||||
"message": "Exit Node aufgrund einer Änderung der Hochverfügbarkeit getrennt."
|
||||
},
|
||||
"event.exitNode.disconnectedUnknown": {
|
||||
"message": "Exit Node aus unbekannten Gründen getrennt."
|
||||
},
|
||||
"event.update.installing": {
|
||||
"message": "Update wird jetzt installiert."
|
||||
},
|
||||
"event.update.completed": {
|
||||
"message": "Ihr NetBird-Client wurde automatisch auf Version {version} aktualisiert."
|
||||
},
|
||||
"event.update.failed": {
|
||||
"message": "Automatisches Update fehlgeschlagen: {reason}"
|
||||
},
|
||||
"common.cancel": {
|
||||
"message": "Abbrechen"
|
||||
},
|
||||
|
||||
@@ -239,90 +239,6 @@
|
||||
"message": "Your NetBird configuration was updated by your IT policy.",
|
||||
"description": "Body of the MDM policy-applied notification, telling the user their settings were changed by their organization's device-management policy."
|
||||
},
|
||||
"event.title": {
|
||||
"message": "{severity}: {category}",
|
||||
"description": "Notification title for a daemon event, composed from severity and category, e.g. \"Warning: DNS\". Keep both placeholders; use your locale's colon spacing."
|
||||
},
|
||||
"event.severity.info": {
|
||||
"message": "Info",
|
||||
"description": "Severity label used in the {severity} slot of event.title. Keep it short."
|
||||
},
|
||||
"event.severity.warning": {
|
||||
"message": "Warning",
|
||||
"description": "Severity label used in the {severity} slot of event.title. Keep it short."
|
||||
},
|
||||
"event.severity.error": {
|
||||
"message": "Error",
|
||||
"description": "Severity label used in the {severity} slot of event.title. Keep it short."
|
||||
},
|
||||
"event.severity.critical": {
|
||||
"message": "Critical",
|
||||
"description": "Severity label used in the {severity} slot of event.title. Keep it short."
|
||||
},
|
||||
"event.category.network": {
|
||||
"message": "Network",
|
||||
"description": "Event category label used in the {category} slot of event.title. Refers to the overlay network."
|
||||
},
|
||||
"event.category.dns": {
|
||||
"message": "DNS",
|
||||
"description": "Event category label used in the {category} slot of event.title. Acronym, do not translate."
|
||||
},
|
||||
"event.category.authentication": {
|
||||
"message": "Authentication",
|
||||
"description": "Event category label used in the {category} slot of event.title. Refers to signing in to the management server."
|
||||
},
|
||||
"event.category.connectivity": {
|
||||
"message": "Connectivity",
|
||||
"description": "Event category label used in the {category} slot of event.title. Refers to reaching peers."
|
||||
},
|
||||
"event.category.system": {
|
||||
"message": "System",
|
||||
"description": "Event category label used in the {category} slot of event.title. Refers to the local machine and the NetBird service."
|
||||
},
|
||||
"event.panic": {
|
||||
"message": "The NetBird service panicked. Please restart the service and submit a bug report with the client logs.",
|
||||
"description": "Notification body after the NetBird background service crashed. \"Service\" is the daemon, not a remote service."
|
||||
},
|
||||
"event.dns.recovered": {
|
||||
"message": "DNS servers are reachable again.",
|
||||
"description": "Notification body when previously unreachable upstream DNS servers respond again."
|
||||
},
|
||||
"event.dns.unreachable": {
|
||||
"message": "Unable to reach one or more DNS servers. This might affect your ability to connect to some services.",
|
||||
"description": "Notification body when one or more upstream DNS servers stop responding."
|
||||
},
|
||||
"event.exitNode.connected": {
|
||||
"message": "Exit node connected.",
|
||||
"description": "Notification body when a full-tunnel exit node becomes active."
|
||||
},
|
||||
"event.exitNode.disconnected": {
|
||||
"message": "Exit node disconnected.",
|
||||
"description": "Notification body when the user or the client shuts the exit node down deliberately."
|
||||
},
|
||||
"event.exitNode.connectionLost": {
|
||||
"message": "Exit node connection lost. Your internet access might be affected.",
|
||||
"description": "Notification body when the exit node peer became unreachable. \"Internet access\" means the user's own browsing."
|
||||
},
|
||||
"event.exitNode.haChange": {
|
||||
"message": "Exit node disconnected due to high availability change.",
|
||||
"description": "Notification body when a high-availability group switched away from this exit node. High availability is the standard IT term."
|
||||
},
|
||||
"event.exitNode.disconnectedUnknown": {
|
||||
"message": "Exit node disconnected for unknown reasons.",
|
||||
"description": "Notification body when the exit node dropped for a reason the client could not classify."
|
||||
},
|
||||
"event.update.installing": {
|
||||
"message": "Installing update now.",
|
||||
"description": "Notification body shown as an automatic client update starts installing."
|
||||
},
|
||||
"event.update.completed": {
|
||||
"message": "Your NetBird client was auto-updated to version {version}.",
|
||||
"description": "Notification body after an automatic client update succeeded. {version} is a version number, keep verbatim."
|
||||
},
|
||||
"event.update.failed": {
|
||||
"message": "Auto-update failed: {reason}",
|
||||
"description": "Notification body when an automatic client update failed. {reason} is an untranslated technical error string; keep your locale's colon spacing."
|
||||
},
|
||||
"common.cancel": {
|
||||
"message": "Cancel",
|
||||
"description": "Generic Cancel button label, reused across dialogs. Keep short."
|
||||
|
||||
@@ -179,69 +179,6 @@
|
||||
"notify.mdm.policyApplied.body": {
|
||||
"message": "Su configuración de NetBird fue actualizada por su política de TI."
|
||||
},
|
||||
"event.title": {
|
||||
"message": "{severity}: {category}"
|
||||
},
|
||||
"event.severity.info": {
|
||||
"message": "Información"
|
||||
},
|
||||
"event.severity.warning": {
|
||||
"message": "Advertencia"
|
||||
},
|
||||
"event.severity.error": {
|
||||
"message": "Error"
|
||||
},
|
||||
"event.severity.critical": {
|
||||
"message": "Crítico"
|
||||
},
|
||||
"event.category.network": {
|
||||
"message": "Red"
|
||||
},
|
||||
"event.category.dns": {
|
||||
"message": "DNS"
|
||||
},
|
||||
"event.category.authentication": {
|
||||
"message": "Autenticación"
|
||||
},
|
||||
"event.category.connectivity": {
|
||||
"message": "Conectividad"
|
||||
},
|
||||
"event.category.system": {
|
||||
"message": "Sistema"
|
||||
},
|
||||
"event.panic": {
|
||||
"message": "El servicio de NetBird falló de forma inesperada. Reinicie el servicio y envíe un informe de error con los registros del cliente."
|
||||
},
|
||||
"event.dns.recovered": {
|
||||
"message": "Los servidores DNS vuelven a estar accesibles."
|
||||
},
|
||||
"event.dns.unreachable": {
|
||||
"message": "No se puede acceder a uno o más servidores DNS. Esto puede afectar la conexión a algunos servicios."
|
||||
},
|
||||
"event.exitNode.connected": {
|
||||
"message": "Nodo de salida conectado."
|
||||
},
|
||||
"event.exitNode.disconnected": {
|
||||
"message": "Nodo de salida desconectado."
|
||||
},
|
||||
"event.exitNode.connectionLost": {
|
||||
"message": "Se perdió la conexión con el nodo de salida. Su acceso a Internet puede verse afectado."
|
||||
},
|
||||
"event.exitNode.haChange": {
|
||||
"message": "Nodo de salida desconectado por un cambio de alta disponibilidad."
|
||||
},
|
||||
"event.exitNode.disconnectedUnknown": {
|
||||
"message": "Nodo de salida desconectado por motivos desconocidos."
|
||||
},
|
||||
"event.update.installing": {
|
||||
"message": "Instalando la actualización ahora."
|
||||
},
|
||||
"event.update.completed": {
|
||||
"message": "Su cliente de NetBird se actualizó automáticamente a la versión {version}."
|
||||
},
|
||||
"event.update.failed": {
|
||||
"message": "La actualización automática falló: {reason}"
|
||||
},
|
||||
"common.cancel": {
|
||||
"message": "Cancelar"
|
||||
},
|
||||
|
||||
@@ -179,69 +179,6 @@
|
||||
"notify.mdm.policyApplied.body": {
|
||||
"message": "Votre configuration NetBird a été mise à jour par votre politique informatique."
|
||||
},
|
||||
"event.title": {
|
||||
"message": "{severity} : {category}"
|
||||
},
|
||||
"event.severity.info": {
|
||||
"message": "Info"
|
||||
},
|
||||
"event.severity.warning": {
|
||||
"message": "Avertissement"
|
||||
},
|
||||
"event.severity.error": {
|
||||
"message": "Erreur"
|
||||
},
|
||||
"event.severity.critical": {
|
||||
"message": "Critique"
|
||||
},
|
||||
"event.category.network": {
|
||||
"message": "Réseau"
|
||||
},
|
||||
"event.category.dns": {
|
||||
"message": "DNS"
|
||||
},
|
||||
"event.category.authentication": {
|
||||
"message": "Authentification"
|
||||
},
|
||||
"event.category.connectivity": {
|
||||
"message": "Connectivité"
|
||||
},
|
||||
"event.category.system": {
|
||||
"message": "Système"
|
||||
},
|
||||
"event.panic": {
|
||||
"message": "Le service NetBird s'est arrêté brutalement. Veuillez redémarrer le service et envoyer un rapport de bug avec les journaux du client."
|
||||
},
|
||||
"event.dns.recovered": {
|
||||
"message": "Les serveurs DNS sont de nouveau joignables."
|
||||
},
|
||||
"event.dns.unreachable": {
|
||||
"message": "Impossible de joindre un ou plusieurs serveurs DNS. Cela peut affecter la connexion à certains services."
|
||||
},
|
||||
"event.exitNode.connected": {
|
||||
"message": "Nœud de sortie connecté."
|
||||
},
|
||||
"event.exitNode.disconnected": {
|
||||
"message": "Nœud de sortie déconnecté."
|
||||
},
|
||||
"event.exitNode.connectionLost": {
|
||||
"message": "Connexion au nœud de sortie perdue. Votre accès à Internet peut être affecté."
|
||||
},
|
||||
"event.exitNode.haChange": {
|
||||
"message": "Nœud de sortie déconnecté suite à un changement de haute disponibilité."
|
||||
},
|
||||
"event.exitNode.disconnectedUnknown": {
|
||||
"message": "Nœud de sortie déconnecté pour une raison inconnue."
|
||||
},
|
||||
"event.update.installing": {
|
||||
"message": "Installation de la mise à jour en cours."
|
||||
},
|
||||
"event.update.completed": {
|
||||
"message": "Votre client NetBird a été mis à jour automatiquement vers la version {version}."
|
||||
},
|
||||
"event.update.failed": {
|
||||
"message": "Échec de la mise à jour automatique : {reason}"
|
||||
},
|
||||
"common.cancel": {
|
||||
"message": "Annuler"
|
||||
},
|
||||
|
||||
@@ -179,69 +179,6 @@
|
||||
"notify.mdm.policyApplied.body": {
|
||||
"message": "A NetBird konfigurációt az IT-szabályzat frissítette."
|
||||
},
|
||||
"event.title": {
|
||||
"message": "{severity}: {category}"
|
||||
},
|
||||
"event.severity.info": {
|
||||
"message": "Információ"
|
||||
},
|
||||
"event.severity.warning": {
|
||||
"message": "Figyelmeztetés"
|
||||
},
|
||||
"event.severity.error": {
|
||||
"message": "Hiba"
|
||||
},
|
||||
"event.severity.critical": {
|
||||
"message": "Kritikus"
|
||||
},
|
||||
"event.category.network": {
|
||||
"message": "Hálózat"
|
||||
},
|
||||
"event.category.dns": {
|
||||
"message": "DNS"
|
||||
},
|
||||
"event.category.authentication": {
|
||||
"message": "Hitelesítés"
|
||||
},
|
||||
"event.category.connectivity": {
|
||||
"message": "Kapcsolat"
|
||||
},
|
||||
"event.category.system": {
|
||||
"message": "Rendszer"
|
||||
},
|
||||
"event.panic": {
|
||||
"message": "A NetBird szolgáltatás összeomlott. Kérjük, indítsa újra a szolgáltatást, és küldjön hibajelentést a kliens naplóival."
|
||||
},
|
||||
"event.dns.recovered": {
|
||||
"message": "A DNS-kiszolgálók ismét elérhetők."
|
||||
},
|
||||
"event.dns.unreachable": {
|
||||
"message": "Egy vagy több DNS-kiszolgáló nem érhető el. Ez befolyásolhatja egyes szolgáltatások elérését."
|
||||
},
|
||||
"event.exitNode.connected": {
|
||||
"message": "Exit Node csatlakoztatva."
|
||||
},
|
||||
"event.exitNode.disconnected": {
|
||||
"message": "Exit Node leválasztva."
|
||||
},
|
||||
"event.exitNode.connectionLost": {
|
||||
"message": "Megszakadt a kapcsolat az Exit Node-dal. Ez érintheti az internetelérést."
|
||||
},
|
||||
"event.exitNode.haChange": {
|
||||
"message": "Az Exit Node leválasztva a magas rendelkezésre állás változása miatt."
|
||||
},
|
||||
"event.exitNode.disconnectedUnknown": {
|
||||
"message": "Az Exit Node ismeretlen okból leválasztva."
|
||||
},
|
||||
"event.update.installing": {
|
||||
"message": "A frissítés telepítése folyamatban."
|
||||
},
|
||||
"event.update.completed": {
|
||||
"message": "A NetBird kliens automatikusan a {version} verzióra frissült."
|
||||
},
|
||||
"event.update.failed": {
|
||||
"message": "Az automatikus frissítés sikertelen: {reason}"
|
||||
},
|
||||
"common.cancel": {
|
||||
"message": "Mégse"
|
||||
},
|
||||
|
||||
@@ -179,69 +179,6 @@
|
||||
"notify.mdm.policyApplied.body": {
|
||||
"message": "La configurazione di NetBird è stata aggiornata dalla policy IT."
|
||||
},
|
||||
"event.title": {
|
||||
"message": "{severity}: {category}"
|
||||
},
|
||||
"event.severity.info": {
|
||||
"message": "Info"
|
||||
},
|
||||
"event.severity.warning": {
|
||||
"message": "Avviso"
|
||||
},
|
||||
"event.severity.error": {
|
||||
"message": "Errore"
|
||||
},
|
||||
"event.severity.critical": {
|
||||
"message": "Critico"
|
||||
},
|
||||
"event.category.network": {
|
||||
"message": "Rete"
|
||||
},
|
||||
"event.category.dns": {
|
||||
"message": "DNS"
|
||||
},
|
||||
"event.category.authentication": {
|
||||
"message": "Autenticazione"
|
||||
},
|
||||
"event.category.connectivity": {
|
||||
"message": "Connettività"
|
||||
},
|
||||
"event.category.system": {
|
||||
"message": "Sistema"
|
||||
},
|
||||
"event.panic": {
|
||||
"message": "Il servizio NetBird si è arrestato in modo anomalo. Riavvii il servizio e invii una segnalazione di bug con i log del client."
|
||||
},
|
||||
"event.dns.recovered": {
|
||||
"message": "I server DNS sono di nuovo raggiungibili."
|
||||
},
|
||||
"event.dns.unreachable": {
|
||||
"message": "Impossibile raggiungere uno o più server DNS. Questo potrebbe influire sulla connessione ad alcuni servizi."
|
||||
},
|
||||
"event.exitNode.connected": {
|
||||
"message": "Nodo di uscita connesso."
|
||||
},
|
||||
"event.exitNode.disconnected": {
|
||||
"message": "Nodo di uscita disconnesso."
|
||||
},
|
||||
"event.exitNode.connectionLost": {
|
||||
"message": "Connessione al nodo di uscita perduta. L'accesso a Internet potrebbe essere compromesso."
|
||||
},
|
||||
"event.exitNode.haChange": {
|
||||
"message": "Nodo di uscita disconnesso a causa di una modifica dell'alta disponibilità."
|
||||
},
|
||||
"event.exitNode.disconnectedUnknown": {
|
||||
"message": "Nodo di uscita disconnesso per motivi sconosciuti."
|
||||
},
|
||||
"event.update.installing": {
|
||||
"message": "Installazione dell'aggiornamento in corso."
|
||||
},
|
||||
"event.update.completed": {
|
||||
"message": "Il client NetBird è stato aggiornato automaticamente alla versione {version}."
|
||||
},
|
||||
"event.update.failed": {
|
||||
"message": "Aggiornamento automatico non riuscito: {reason}"
|
||||
},
|
||||
"common.cancel": {
|
||||
"message": "Annulla"
|
||||
},
|
||||
|
||||
@@ -179,69 +179,6 @@
|
||||
"notify.mdm.policyApplied.body": {
|
||||
"message": "NetBird の構成が IT ポリシーによって更新されました。"
|
||||
},
|
||||
"event.title": {
|
||||
"message": "{severity}: {category}"
|
||||
},
|
||||
"event.severity.info": {
|
||||
"message": "情報"
|
||||
},
|
||||
"event.severity.warning": {
|
||||
"message": "警告"
|
||||
},
|
||||
"event.severity.error": {
|
||||
"message": "エラー"
|
||||
},
|
||||
"event.severity.critical": {
|
||||
"message": "重大"
|
||||
},
|
||||
"event.category.network": {
|
||||
"message": "ネットワーク"
|
||||
},
|
||||
"event.category.dns": {
|
||||
"message": "DNS"
|
||||
},
|
||||
"event.category.authentication": {
|
||||
"message": "認証"
|
||||
},
|
||||
"event.category.connectivity": {
|
||||
"message": "接続"
|
||||
},
|
||||
"event.category.system": {
|
||||
"message": "システム"
|
||||
},
|
||||
"event.panic": {
|
||||
"message": "NetBird サービスがクラッシュしました。サービスを再起動し、クライアントログを添えてバグを報告してください。"
|
||||
},
|
||||
"event.dns.recovered": {
|
||||
"message": "DNS サーバーに再び到達できるようになりました。"
|
||||
},
|
||||
"event.dns.unreachable": {
|
||||
"message": "1 つ以上の DNS サーバーに到達できません。一部のサービスへの接続に影響する可能性があります。"
|
||||
},
|
||||
"event.exitNode.connected": {
|
||||
"message": "出口ノードに接続しました。"
|
||||
},
|
||||
"event.exitNode.disconnected": {
|
||||
"message": "出口ノードの接続を解除しました。"
|
||||
},
|
||||
"event.exitNode.connectionLost": {
|
||||
"message": "出口ノードとの接続が失われました。インターネット接続に影響する可能性があります。"
|
||||
},
|
||||
"event.exitNode.haChange": {
|
||||
"message": "高可用性の変更により出口ノードの接続が解除されました。"
|
||||
},
|
||||
"event.exitNode.disconnectedUnknown": {
|
||||
"message": "不明な理由により出口ノードの接続が解除されました。"
|
||||
},
|
||||
"event.update.installing": {
|
||||
"message": "更新をインストールしています。"
|
||||
},
|
||||
"event.update.completed": {
|
||||
"message": "NetBird クライアントがバージョン {version} に自動更新されました。"
|
||||
},
|
||||
"event.update.failed": {
|
||||
"message": "自動更新に失敗しました: {reason}"
|
||||
},
|
||||
"common.cancel": {
|
||||
"message": "キャンセル"
|
||||
},
|
||||
|
||||
@@ -179,69 +179,6 @@
|
||||
"notify.mdm.policyApplied.body": {
|
||||
"message": "A sua configuração do NetBird foi atualizada pela política de TI."
|
||||
},
|
||||
"event.title": {
|
||||
"message": "{severity}: {category}"
|
||||
},
|
||||
"event.severity.info": {
|
||||
"message": "Informação"
|
||||
},
|
||||
"event.severity.warning": {
|
||||
"message": "Aviso"
|
||||
},
|
||||
"event.severity.error": {
|
||||
"message": "Erro"
|
||||
},
|
||||
"event.severity.critical": {
|
||||
"message": "Crítico"
|
||||
},
|
||||
"event.category.network": {
|
||||
"message": "Rede"
|
||||
},
|
||||
"event.category.dns": {
|
||||
"message": "DNS"
|
||||
},
|
||||
"event.category.authentication": {
|
||||
"message": "Autenticação"
|
||||
},
|
||||
"event.category.connectivity": {
|
||||
"message": "Conectividade"
|
||||
},
|
||||
"event.category.system": {
|
||||
"message": "Sistema"
|
||||
},
|
||||
"event.panic": {
|
||||
"message": "O serviço NetBird falhou de forma inesperada. Reinicie o serviço e envie um relatório de erro com os registros do cliente."
|
||||
},
|
||||
"event.dns.recovered": {
|
||||
"message": "Os servidores DNS estão novamente acessíveis."
|
||||
},
|
||||
"event.dns.unreachable": {
|
||||
"message": "Não é possível acessar um ou mais servidores DNS. Isto pode afetar a conexão a alguns serviços."
|
||||
},
|
||||
"event.exitNode.connected": {
|
||||
"message": "Nó de saída conectado."
|
||||
},
|
||||
"event.exitNode.disconnected": {
|
||||
"message": "Nó de saída desconectado."
|
||||
},
|
||||
"event.exitNode.connectionLost": {
|
||||
"message": "Conexão com o nó de saída perdida. O seu acesso à Internet pode ser afetado."
|
||||
},
|
||||
"event.exitNode.haChange": {
|
||||
"message": "Nó de saída desconectado devido a uma alteração de alta disponibilidade."
|
||||
},
|
||||
"event.exitNode.disconnectedUnknown": {
|
||||
"message": "Nó de saída desconectado por motivos desconhecidos."
|
||||
},
|
||||
"event.update.installing": {
|
||||
"message": "Instalando a atualização agora."
|
||||
},
|
||||
"event.update.completed": {
|
||||
"message": "O seu cliente NetBird foi atualizado automaticamente para a versão {version}."
|
||||
},
|
||||
"event.update.failed": {
|
||||
"message": "Falha na atualização automática: {reason}"
|
||||
},
|
||||
"common.cancel": {
|
||||
"message": "Cancelar"
|
||||
},
|
||||
|
||||
@@ -179,69 +179,6 @@
|
||||
"notify.mdm.policyApplied.body": {
|
||||
"message": "Конфигурация NetBird была обновлена в соответствии с вашей ИТ-политикой."
|
||||
},
|
||||
"event.title": {
|
||||
"message": "{severity}: {category}"
|
||||
},
|
||||
"event.severity.info": {
|
||||
"message": "Информация"
|
||||
},
|
||||
"event.severity.warning": {
|
||||
"message": "Предупреждение"
|
||||
},
|
||||
"event.severity.error": {
|
||||
"message": "Ошибка"
|
||||
},
|
||||
"event.severity.critical": {
|
||||
"message": "Критично"
|
||||
},
|
||||
"event.category.network": {
|
||||
"message": "Сеть"
|
||||
},
|
||||
"event.category.dns": {
|
||||
"message": "DNS"
|
||||
},
|
||||
"event.category.authentication": {
|
||||
"message": "Аутентификация"
|
||||
},
|
||||
"event.category.connectivity": {
|
||||
"message": "Связь"
|
||||
},
|
||||
"event.category.system": {
|
||||
"message": "Система"
|
||||
},
|
||||
"event.panic": {
|
||||
"message": "Служба NetBird аварийно завершилась. Перезапустите службу и отправьте отчёт об ошибке с журналами клиента."
|
||||
},
|
||||
"event.dns.recovered": {
|
||||
"message": "DNS-серверы снова доступны."
|
||||
},
|
||||
"event.dns.unreachable": {
|
||||
"message": "Не удалось связаться с одним или несколькими DNS-серверами. Это может повлиять на подключение к некоторым сервисам."
|
||||
},
|
||||
"event.exitNode.connected": {
|
||||
"message": "Выходной узел подключён."
|
||||
},
|
||||
"event.exitNode.disconnected": {
|
||||
"message": "Выходной узел отключён."
|
||||
},
|
||||
"event.exitNode.connectionLost": {
|
||||
"message": "Соединение с выходным узлом потеряно. Доступ в интернет может быть нарушен."
|
||||
},
|
||||
"event.exitNode.haChange": {
|
||||
"message": "Выходной узел отключён из-за изменения конфигурации высокой доступности."
|
||||
},
|
||||
"event.exitNode.disconnectedUnknown": {
|
||||
"message": "Выходной узел отключён по неизвестной причине."
|
||||
},
|
||||
"event.update.installing": {
|
||||
"message": "Устанавливается обновление."
|
||||
},
|
||||
"event.update.completed": {
|
||||
"message": "Клиент NetBird автоматически обновлён до версии {version}."
|
||||
},
|
||||
"event.update.failed": {
|
||||
"message": "Не удалось выполнить автоматическое обновление: {reason}"
|
||||
},
|
||||
"common.cancel": {
|
||||
"message": "Отмена"
|
||||
},
|
||||
|
||||
@@ -179,69 +179,6 @@
|
||||
"notify.mdm.policyApplied.body": {
|
||||
"message": "您的 NetBird 配置已根据 IT 策略更新。"
|
||||
},
|
||||
"event.title": {
|
||||
"message": "{severity}:{category}"
|
||||
},
|
||||
"event.severity.info": {
|
||||
"message": "信息"
|
||||
},
|
||||
"event.severity.warning": {
|
||||
"message": "警告"
|
||||
},
|
||||
"event.severity.error": {
|
||||
"message": "错误"
|
||||
},
|
||||
"event.severity.critical": {
|
||||
"message": "严重"
|
||||
},
|
||||
"event.category.network": {
|
||||
"message": "网络"
|
||||
},
|
||||
"event.category.dns": {
|
||||
"message": "DNS"
|
||||
},
|
||||
"event.category.authentication": {
|
||||
"message": "身份验证"
|
||||
},
|
||||
"event.category.connectivity": {
|
||||
"message": "连接"
|
||||
},
|
||||
"event.category.system": {
|
||||
"message": "系统"
|
||||
},
|
||||
"event.panic": {
|
||||
"message": "NetBird 服务发生崩溃。请重启该服务,并附上客户端日志提交错误报告。"
|
||||
},
|
||||
"event.dns.recovered": {
|
||||
"message": "DNS 服务器已恢复可访问。"
|
||||
},
|
||||
"event.dns.unreachable": {
|
||||
"message": "无法访问一个或多个 DNS 服务器。这可能影响您连接部分服务。"
|
||||
},
|
||||
"event.exitNode.connected": {
|
||||
"message": "出口节点已连接。"
|
||||
},
|
||||
"event.exitNode.disconnected": {
|
||||
"message": "出口节点已断开。"
|
||||
},
|
||||
"event.exitNode.connectionLost": {
|
||||
"message": "与出口节点的连接已丢失。您的互联网访问可能受到影响。"
|
||||
},
|
||||
"event.exitNode.haChange": {
|
||||
"message": "由于高可用性变更,出口节点已断开。"
|
||||
},
|
||||
"event.exitNode.disconnectedUnknown": {
|
||||
"message": "出口节点因未知原因已断开。"
|
||||
},
|
||||
"event.update.installing": {
|
||||
"message": "正在安装更新。"
|
||||
},
|
||||
"event.update.completed": {
|
||||
"message": "NetBird 客户端已自动更新到版本 {version}。"
|
||||
},
|
||||
"event.update.failed": {
|
||||
"message": "自动更新失败:{reason}"
|
||||
},
|
||||
"common.cancel": {
|
||||
"message": "取消"
|
||||
},
|
||||
|
||||
@@ -63,20 +63,6 @@ func (l *Localizer) T(key string, args ...string) string {
|
||||
return l.bundle.Translate(lang, key, args...)
|
||||
}
|
||||
|
||||
// Lookup resolves a key supplied at runtime by the daemon, substituting args as
|
||||
// {placeholder}/value pairs. It reports false when the key is in no bundle, so
|
||||
// the caller can fall back to the daemon's own English text instead of showing a
|
||||
// bare key. An empty key never resolves.
|
||||
func (l *Localizer) Lookup(key string, args map[string]string) (string, bool) {
|
||||
if l == nil || l.bundle == nil || key == "" {
|
||||
return "", false
|
||||
}
|
||||
l.mu.RLock()
|
||||
lang := l.lang
|
||||
l.mu.RUnlock()
|
||||
return l.bundle.Lookup(lang, key, flattenArgs(args)...)
|
||||
}
|
||||
|
||||
// Watch invokes cb on each language change, after the cached language is
|
||||
// updated so cb may call l.T with the new locale. Replaces any prior subscription.
|
||||
func (l *Localizer) Watch(cb func(lang i18n.LanguageCode)) {
|
||||
@@ -142,17 +128,3 @@ func (l *Localizer) StatusLabel(status string) string {
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
// flattenArgs turns a placeholder map into the flat name/value slice the bundle
|
||||
// takes. Iteration order is irrelevant: each pair substitutes an independent
|
||||
// {name}.
|
||||
func flattenArgs(args map[string]string) []string {
|
||||
if len(args) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, 0, len(args)*2)
|
||||
for name, value := range args {
|
||||
out = append(out, name, value)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -59,21 +59,13 @@ type Emitter interface {
|
||||
|
||||
// SystemEvent is the frontend-facing shape of a daemon SystemEvent.
|
||||
type SystemEvent struct {
|
||||
ID string `json:"id"`
|
||||
Severity string `json:"severity"`
|
||||
Category string `json:"category"`
|
||||
Message string `json:"message"`
|
||||
UserMessage string `json:"userMessage"`
|
||||
// MessageKey names the localizable body for this event; empty on control
|
||||
// events and on events from a daemon that predates the field. Resolve it
|
||||
// against the UI bundle and fall back to UserMessage on a miss.
|
||||
MessageKey string `json:"messageKey"`
|
||||
MessageArgs map[string]string `json:"messageArgs"`
|
||||
// TitleKey names the localizable notification title, empty when the event
|
||||
// has none and the consumer should compose one from severity and category.
|
||||
TitleKey string `json:"titleKey"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
Metadata map[string]string `json:"metadata"`
|
||||
ID string `json:"id"`
|
||||
Severity string `json:"severity"`
|
||||
Category string `json:"category"`
|
||||
Message string `json:"message"`
|
||||
UserMessage string `json:"userMessage"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
Metadata map[string]string `json:"metadata"`
|
||||
}
|
||||
|
||||
// PeerStatus is the frontend-facing shape of a daemon PeerState.
|
||||
@@ -571,9 +563,6 @@ func systemEventFromProto(e *proto.SystemEvent) SystemEvent {
|
||||
Category: strings.ToLower(strings.TrimPrefix(e.GetCategory().String(), "SystemEvent_")),
|
||||
Message: e.GetMessage(),
|
||||
UserMessage: e.GetUserMessage(),
|
||||
MessageKey: e.GetMessageKey(),
|
||||
MessageArgs: e.GetMessageArgs(),
|
||||
TitleKey: e.GetTitleKey(),
|
||||
Metadata: map[string]string{},
|
||||
}
|
||||
if ts := e.GetTimestamp(); ts != nil {
|
||||
|
||||
@@ -26,6 +26,7 @@ const (
|
||||
notifyIDUpdatePrefix = "netbird-update-"
|
||||
notifyIDEvent = "netbird-event-"
|
||||
notifyIDTrayError = "netbird-tray-error"
|
||||
notifyIDMDMPolicy = "netbird-mdm-policy"
|
||||
|
||||
statusError = "Error"
|
||||
|
||||
|
||||
@@ -21,14 +21,32 @@ func (t *Tray) onSystemEvent(ev *application.CustomEvent) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// config_changed carries no user-facing message, so handle it before the gate below.
|
||||
// config_changed carries no UserMessage, so handle it before the message gate below.
|
||||
if se.Category == "system" && se.Metadata[proto.MetadataTypeKey] == proto.MetadataTypeConfigChanged {
|
||||
log.Infof("config_changed event received (source=%s); refreshing tray restrictions", se.Metadata[proto.MetadataSourceKey])
|
||||
go t.refreshRestrictions()
|
||||
go t.loadConfig()
|
||||
// MDM gets a localised toast here; the daemon's English "policy_applied"
|
||||
// event is suppressed in shouldSkipSystemEvent. Other sources stay silent.
|
||||
if se.Metadata[proto.MetadataSourceKey] == proto.MetadataSourceMDM {
|
||||
t.profileMu.Lock()
|
||||
enabled := t.notificationsEnabled
|
||||
t.profileMu.Unlock()
|
||||
if enabled {
|
||||
t.notify(
|
||||
t.loc.T("notify.mdm.policyApplied.title"),
|
||||
t.loc.T("notify.mdm.policyApplied.body"),
|
||||
notifyIDMDMPolicy,
|
||||
)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if se.MessageKey == "" && se.UserMessage == "" {
|
||||
// Session-warning and deadline-rejected events build their body locally from
|
||||
// metadata; every other event needs a UserMessage.
|
||||
isSessionWarning := se.Metadata[authsession.MetaWarning] == "true"
|
||||
isDeadlineRejected := se.Metadata[authsession.MetaDeadlineRejected] != ""
|
||||
if !isSessionWarning && !isDeadlineRejected && se.UserMessage == "" {
|
||||
return
|
||||
}
|
||||
if shouldSkipSystemEvent(se) {
|
||||
@@ -43,56 +61,56 @@ func (t *Tray) onSystemEvent(ev *application.CustomEvent) {
|
||||
return
|
||||
}
|
||||
|
||||
body := t.localizedEventMessage(se)
|
||||
// Session-warning events route via stable metadata flags rather than
|
||||
// category/severity so a daemon-side reword still lands here. Final warning
|
||||
// auto-opens the SessionExpiration dialog with no notification (the dialog is
|
||||
// the last-chance reminder; doubling up would be noise).
|
||||
if isDeadlineRejected {
|
||||
t.notify(
|
||||
t.loc.T("notify.sessionDeadlineRejected.title"),
|
||||
t.loc.T("notify.sessionDeadlineRejected.body"),
|
||||
notifyIDSessionExpired,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// The final session warning auto-opens the SessionExpiration dialog instead of
|
||||
// toasting: the dialog is the last-chance reminder and doubling up would be
|
||||
// noise. This routes on metadata rather than the message key because it is a
|
||||
// behavioural distinction, not a wording one.
|
||||
if se.Metadata[authsession.MetaWarning] == "true" {
|
||||
if se.Metadata != nil && se.Metadata[authsession.MetaWarning] == "true" {
|
||||
if se.Metadata[authsession.MetaFinal] == "true" {
|
||||
t.openSessionExpiration()
|
||||
return
|
||||
}
|
||||
t.notifySessionWarning(t.eventTitle(se), body)
|
||||
t.notifySessionWarning(
|
||||
t.loc.T("notify.sessionWarning.title"),
|
||||
t.buildSessionWarningBody(se.Metadata),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
body := se.UserMessage
|
||||
if id := se.Metadata["id"]; id != "" {
|
||||
body += fmt.Sprintf(" ID: %s", id)
|
||||
}
|
||||
t.notify(t.eventTitle(se), body, notifyIDEvent+se.ID)
|
||||
t.notify(eventTitle(se), body, notifyIDEvent+se.ID)
|
||||
}
|
||||
|
||||
// localizedEventMessage resolves the daemon's message key against the active
|
||||
// locale. A key this build does not ship — a daemon newer than the UI — falls
|
||||
// back to the daemon's own English rendering rather than showing a bare key.
|
||||
func (t *Tray) localizedEventMessage(se services.SystemEvent) string {
|
||||
if body, ok := t.loc.Lookup(se.MessageKey, se.MessageArgs); ok {
|
||||
return body
|
||||
// eventTitle composes a notification title, e.g. "Critical: DNS", "Warning: Authentication".
|
||||
func eventTitle(e services.SystemEvent) string {
|
||||
prefix := titleCase(e.Severity)
|
||||
if prefix == "" {
|
||||
prefix = "Info"
|
||||
}
|
||||
if se.MessageKey != "" {
|
||||
log.Debugf("no translation for event message key %q, using the daemon's text", se.MessageKey)
|
||||
category := titleCase(e.Category)
|
||||
if category == "" {
|
||||
category = "System"
|
||||
}
|
||||
return se.UserMessage
|
||||
return prefix + ": " + category
|
||||
}
|
||||
|
||||
// eventTitle resolves the event's own title key, falling back to a title
|
||||
// composed from severity and category, e.g. "Critical: DNS" in English. An enum
|
||||
// value this build does not know falls back to the Info and System labels.
|
||||
func (t *Tray) eventTitle(se services.SystemEvent) string {
|
||||
if title, ok := t.loc.Lookup(se.TitleKey, nil); ok {
|
||||
return title
|
||||
func titleCase(s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
severity, ok := t.loc.Lookup("event.severity."+strings.ToLower(se.Severity), nil)
|
||||
if !ok {
|
||||
severity = t.loc.T("event.severity.info")
|
||||
}
|
||||
category, ok := t.loc.Lookup("event.category."+strings.ToLower(se.Category), nil)
|
||||
if !ok {
|
||||
category = t.loc.T("event.category.system")
|
||||
}
|
||||
return t.loc.T("event.title", "severity", severity, "category", category)
|
||||
return strings.ToUpper(s[:1]) + strings.ToLower(s[1:])
|
||||
}
|
||||
|
||||
// shouldSkipSystemEvent reports whether a daemon SystemEvent must not surface as
|
||||
@@ -101,6 +119,11 @@ func (t *Tray) eventTitle(se services.SystemEvent) string {
|
||||
// - install-progress signals (consumed by the install-progress window)
|
||||
// - the ::/0 partner of an exit-node default route (0.0.0.0/0 already toasted)
|
||||
func shouldSkipSystemEvent(se services.SystemEvent) bool {
|
||||
// "policy_applied" carries a hardcoded English message; the localised toast
|
||||
// fires on the paired config_changed (source=mdm) event instead.
|
||||
if se.Metadata[proto.MetadataTypeKey] == proto.MetadataTypePolicyApplied {
|
||||
return true
|
||||
}
|
||||
if _, isUpdate := se.Metadata["new_version_available"]; isUpdate {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -1,150 +0,0 @@
|
||||
//go:build !android && !ios && !freebsd && !js
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/netbirdio/netbird/client/proto"
|
||||
"github.com/netbirdio/netbird/client/ui/i18n"
|
||||
"github.com/netbirdio/netbird/client/ui/services"
|
||||
)
|
||||
|
||||
// trayWithLocalizer builds the minimum Tray the message/title resolvers touch:
|
||||
// they read t.loc and nothing else, so no app, window or daemon connection is
|
||||
// needed. The shipped locale tree is used so the assertions below exercise the
|
||||
// real bundles rather than a fixture.
|
||||
func trayWithLocalizer(t *testing.T) *Tray {
|
||||
t.Helper()
|
||||
bundle, err := i18n.NewBundle(os.DirFS("i18n/locales"))
|
||||
require.NoError(t, err, "the shipped locale tree must load")
|
||||
return &Tray{loc: NewLocalizer(bundle, nil)}
|
||||
}
|
||||
|
||||
func TestLocalizedEventMessageResolvesKey(t *testing.T) {
|
||||
tray := trayWithLocalizer(t)
|
||||
|
||||
got := tray.localizedEventMessage(services.SystemEvent{
|
||||
MessageKey: string(proto.UserMsgExitNodeConnected),
|
||||
// A daemon always ships its English rendering too; the key must win.
|
||||
UserMessage: "should not be used",
|
||||
})
|
||||
assert.Equal(t, "Exit node connected.", got)
|
||||
}
|
||||
|
||||
func TestLocalizedEventMessageSubstitutesArgs(t *testing.T) {
|
||||
tray := trayWithLocalizer(t)
|
||||
|
||||
got := tray.localizedEventMessage(services.SystemEvent{
|
||||
MessageKey: string(proto.UserMsgUpdateCompleted),
|
||||
MessageArgs: map[string]string{proto.ArgVersion: "0.60.1"},
|
||||
})
|
||||
assert.Equal(t, "Your NetBird client was auto-updated to version 0.60.1.", got)
|
||||
}
|
||||
|
||||
// A daemon newer than the UI can publish a key this build has never heard of.
|
||||
// Showing the raw key would be a visible regression, so the daemon's own English
|
||||
// text has to win instead.
|
||||
func TestLocalizedEventMessageFallsBackToDaemonText(t *testing.T) {
|
||||
tray := trayWithLocalizer(t)
|
||||
|
||||
got := tray.localizedEventMessage(services.SystemEvent{
|
||||
MessageKey: "event.somethingThisBuildNeverHeardOf",
|
||||
UserMessage: "A message from a newer daemon.",
|
||||
})
|
||||
assert.Equal(t, "A message from a newer daemon.", got)
|
||||
}
|
||||
|
||||
// An old daemon sends no key at all, only userMessage.
|
||||
func TestLocalizedEventMessageWithoutKey(t *testing.T) {
|
||||
tray := trayWithLocalizer(t)
|
||||
|
||||
got := tray.localizedEventMessage(services.SystemEvent{UserMessage: "Legacy English text."})
|
||||
assert.Equal(t, "Legacy English text.", got)
|
||||
}
|
||||
|
||||
func TestEventTitlePrefersTitleKey(t *testing.T) {
|
||||
tray := trayWithLocalizer(t)
|
||||
|
||||
got := tray.eventTitle(services.SystemEvent{
|
||||
Severity: "critical",
|
||||
Category: "authentication",
|
||||
TitleKey: string(proto.TitleSessionWarning),
|
||||
})
|
||||
assert.Equal(t, "Session expires soon", got, "a title key must beat the composed title")
|
||||
}
|
||||
|
||||
func TestEventTitleComposesFromSeverityAndCategory(t *testing.T) {
|
||||
tray := trayWithLocalizer(t)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
severity string
|
||||
category string
|
||||
want string
|
||||
}{
|
||||
{"warning dns", "warning", "dns", "Warning: DNS"},
|
||||
{"critical system", "critical", "system", "Critical: System"},
|
||||
{"info network", "info", "network", "Info: Network"},
|
||||
{"error authentication", "error", "authentication", "Error: Authentication"},
|
||||
// Enum values this build does not know, and the empty severity/category
|
||||
// an event carries before the daemon fills them in.
|
||||
{"unknown severity", "apocalyptic", "dns", "Info: DNS"},
|
||||
{"unknown category", "warning", "quantum", "Warning: System"},
|
||||
{"empty", "", "", "Info: System"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := tray.eventTitle(services.SystemEvent{Severity: tc.severity, Category: tc.category})
|
||||
assert.Equal(t, tc.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldSkipSystemEvent(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ev services.SystemEvent
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "update announcement handled by the tray updater",
|
||||
ev: services.SystemEvent{Metadata: map[string]string{"new_version_available": "0.60.1"}},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "install progress belongs to the progress window",
|
||||
ev: services.SystemEvent{Metadata: map[string]string{"progress_window": "show"}},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "the v6 half of a dual-stack default route is already toasted as v4",
|
||||
ev: services.SystemEvent{Category: "network", Metadata: map[string]string{"network": "::/0"}},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "the v4 default route is the one that toasts",
|
||||
ev: services.SystemEvent{Category: "network", Metadata: map[string]string{"network": "0.0.0.0/0"}},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
// policy_applied used to be suppressed here while the tray toasted
|
||||
// off the paired config_changed event; it now carries its own keys.
|
||||
name: "mdm policy applied surfaces normally",
|
||||
ev: services.SystemEvent{
|
||||
MessageKey: string(proto.UserMsgMDMPolicyApplied),
|
||||
Metadata: map[string]string{proto.MetadataTypeKey: proto.MetadataTypePolicyApplied},
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert.Equal(t, tc.want, shouldSkipSystemEvent(tc.ev))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/wailsapp/wails/v3/pkg/services/notifications"
|
||||
|
||||
nbstatus "github.com/netbirdio/netbird/client/status"
|
||||
"github.com/netbirdio/netbird/client/ui/authsession"
|
||||
"github.com/netbirdio/netbird/client/ui/services"
|
||||
)
|
||||
|
||||
@@ -194,6 +196,25 @@ func (t *Tray) registerSessionWarningCategory() {
|
||||
})
|
||||
}
|
||||
|
||||
// buildSessionWarningBody composes the localised notification body from the daemon's metadata.
|
||||
// The daemon has no locale, so it ships an RFC3339 deadline the tray turns into a user-language sentence.
|
||||
// Falls back to a generic string when metadata is missing or unparsable.
|
||||
func (t *Tray) buildSessionWarningBody(meta map[string]string) string {
|
||||
if meta == nil {
|
||||
return t.loc.T("notify.sessionWarning.bodyGeneric")
|
||||
}
|
||||
raw := meta[authsession.MetaExpiresAt]
|
||||
if raw == "" {
|
||||
return t.loc.T("notify.sessionWarning.bodyGeneric")
|
||||
}
|
||||
deadline, err := authsession.ParseExpiresAt(raw)
|
||||
if err != nil {
|
||||
return t.loc.T("notify.sessionWarning.bodyGeneric")
|
||||
}
|
||||
remaining := nbstatus.FormatRemainingDuration(time.Until(deadline))
|
||||
return t.loc.T("notify.sessionWarning.body", "remaining", remaining)
|
||||
}
|
||||
|
||||
// notifySessionWarning sends the interactive expiry notification, falling back to plain notify when the
|
||||
// with-actions variant is unavailable (older platform impls, or a bare Notifier in tests).
|
||||
func (t *Tray) notifySessionWarning(title, body string) {
|
||||
|
||||
@@ -115,7 +115,7 @@ sequenceDiagram
|
||||
Resp->>Resp: parse usage tokens, completion
|
||||
Note over Resp: capture_completion gates raw<br/>completion capture
|
||||
Resp->>Cost: tokens
|
||||
Cost->>Cost: lookup pricing.yaml + compute cost
|
||||
Cost->>Cost: lookup rates from config-delivered<br/>pricing table + compute cost
|
||||
Cost->>Rec: tokens + cost
|
||||
Rec->>MgmtGrpc: RecordLLMUsage(provider, model, prompt_t, completion_t, cost, groups, user)
|
||||
Rec-->>Log: emit access-log entry<br/>(if EnableLogCollection)
|
||||
|
||||
@@ -15,6 +15,10 @@ Inside the package: `manager.go` is the CRUD + permissions-gated facade; `synthe
|
||||
| ---- | ---- |
|
||||
| `agentnetwork/manager.go` | Manager interface + CRUD + permission gates + bootstrap-settings + reconcile trigger |
|
||||
| `agentnetwork/synthesizer.go` | Settings/policy → wire-format synthesis; sole writer of the proxy middleware chain |
|
||||
| `agentnetwork/synthesizer_pricing.go` | `buildCostMeterConfigJSON` — default table + per-provider prices → `cost_meter` config |
|
||||
| `agentnetwork/pricing/defaults.go` | Default pricing table derived from the catalog + supplementals; `DefaultTable`, `LookupDefault`, wire `Entry` |
|
||||
| `agentnetwork/pricing/override.go` | `LoadFile`/`StartReloader` for `AgentNetwork.PricingDefaultsFile` (mtime poll, merge over compiled-in base) |
|
||||
| `agentnetwork/pricing/{exampleyaml,gen}.go` | Generates `defaults_llm_pricing.example.yaml` from the compiled-in table (golden-tested) |
|
||||
| `agentnetwork/policyselect.go` | Per-request policy attribution + account-budget ceiling (min-wins) |
|
||||
| `agentnetwork/reconcile.go` | Per-account synth diff vs in-memory cache → Create/Update/Delete |
|
||||
| `agentnetwork/catalog/catalog.go` | Static provider catalogue (auth headers, identity-injection shapes) |
|
||||
@@ -48,6 +52,8 @@ flowchart TD
|
||||
I --> J[indexProviderGroups: providerID -> sorted source groups]
|
||||
J --> K[buildRouterConfigJSON drops orphan providers]
|
||||
J --> L[buildIdentityInjectConfigJSON per catalog entry]
|
||||
J --> K2[buildCostMeterConfigJSON: default table + per-provider prices]
|
||||
K2 --> P
|
||||
H --> M[mergeGuardrails: union allowlist, OR redact]
|
||||
M --> N[applyAccountCollectionControls account toggle = SOLE capture control]
|
||||
N --> O[marshalGuardrailConfig]
|
||||
@@ -60,6 +66,84 @@ flowchart TD
|
||||
R --> T[accountManager.UpdateAccountPeers — fans synth ACLs into network map]
|
||||
```
|
||||
|
||||
### LLM pricing (management is the sole authority)
|
||||
|
||||
**The proxy carries no price list.** Management synthesizes the entire pricing
|
||||
table and ships it inside `cost_meter`'s `ConfigJSON`, so a price change reaches
|
||||
the proxies as an ordinary mapping push — the chain rebuild installs a fresh
|
||||
table and there is nothing to reload on the proxy side.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[catalog.All — PricingSurfaces x Models] --> B[buildDefaultTable + supplementalDefaults]
|
||||
B --> C{AgentNetwork.PricingDefaultsFile}
|
||||
C -- absent --> D[compiled-in table serves]
|
||||
C -- loaded --> E[LoadFile: merge file entries WHOLE over compiled base]
|
||||
E --> F[mergedTable atomic.Pointer]
|
||||
D --> G[DefaultTable]
|
||||
F --> G
|
||||
G --> H[buildCostMeterConfigJSON — pricing.defaults]
|
||||
I[types.Provider.Models operator prices] --> J[normalizePricingModelID<br/>bedrock ARN/region/version, vertex @version]
|
||||
J --> K[materializeEntry: default entry as base,<br/>operator input/output verbatim,<br/>cache pointers only when non-nil]
|
||||
K --> L[pricing.providers keyed by provider record ID]
|
||||
H --> M[cost_meter ConfigJSON]
|
||||
L --> M
|
||||
G --> N[GET /catalog — applyDefaultPricing prefills dashboard rows]
|
||||
O[StartReloader: mtime poll every ReloadInterval 1m] --> E
|
||||
```
|
||||
|
||||
**Two tiers, resolved per request on the proxy** (`synthesizer_pricing.go:22-35`):
|
||||
|
||||
- `pricing.defaults` — surface (`openai`/`anthropic`/`bedrock`) → normalized model
|
||||
id → rates. The **full** default table ships to every account: it is small
|
||||
(~10 KB) and it is what keeps gateway-style providers (which enumerate no
|
||||
models, so they claim every model) priced.
|
||||
- `pricing.providers` — provider **record** id → normalized model id → rates,
|
||||
matched against the `llm.resolved_provider_id` the router stamps. Entries are
|
||||
**fully materialized here**, at synth time: `materializeEntry` starts from the
|
||||
default entry for that model so cache rates the operator didn't state are
|
||||
inherited, overlays operator `input`/`output` verbatim (**including an explicit
|
||||
0**, which prices a self-hosted or internal endpoint as free rather than
|
||||
silently reverting to list price), and overlays cache-rate **pointers only when
|
||||
non-nil** — `nil` means "inherit the default", an explicit `0` means "no
|
||||
discount, bill this bucket at the input rate". The proxy therefore does two map
|
||||
lookups and no merging.
|
||||
|
||||
Same orphan rule as the router: a provider no enabled policy authorises is
|
||||
unreachable, so its prices aren't shipped. Model ids are normalized with the
|
||||
**same** functions the request parser uses (`NormalizeBedrockModel` /
|
||||
`NormalizeVertexModel`), which is what makes the per-record lookup key compare
|
||||
equal to the `llm.model` the proxy meters. Post-normalization duplicates resolve
|
||||
first-occurrence-wins, matching the routing dedup order.
|
||||
|
||||
**`AgentNetwork.PricingDefaultsFile`** (`config.go:190-207`) lets an operator
|
||||
replace default rates without a rebuild. Schema is `surface → model → rates`
|
||||
(`input_per_1k`, `output_per_1k`, and optional `cached_input_per_1k` /
|
||||
`cache_read_per_1k` / `cache_creation_per_1k`). Semantics:
|
||||
|
||||
- A **relative** path resolves against `<Datadir>`, so a bare filename lands
|
||||
alongside the store. Empty config probes `<Datadir>/defaults_llm_pricing.yaml`.
|
||||
- An **explicitly configured** path is *required to load*: a typo or malformed
|
||||
file fails startup, because the operator believes those rates are live. The
|
||||
conventional probe is optional — an absent file just serves compiled-in
|
||||
defaults, and the path stays watched in case it appears later.
|
||||
- File entries **replace** the compiled-in entry for the same (surface, model)
|
||||
**whole** — they are not field-merged, so an entry must repeat the cache rates
|
||||
it wants to keep. Everything the file doesn't mention keeps built-in rates.
|
||||
- Unknown YAML fields are rejected (`KnownFields(true)`) and every rate must be
|
||||
finite and non-negative — the same constraints the HTTP API enforces on
|
||||
operator per-provider prices.
|
||||
- Reload is an mtime poll (`ReloadInterval`, 1 min) and is **lenient at runtime**:
|
||||
a parse error keeps the previous table, a deleted file reverts to compiled-in
|
||||
defaults. A mid-edit save can never take pricing down.
|
||||
|
||||
The live table feeds **both** consumers, which is what keeps them consistent: the
|
||||
synthesizer (what proxies actually bill with) and `GET /api/agent-network/catalog`
|
||||
via `applyDefaultPricing` (what the dashboard's model-row prices prefill with).
|
||||
`defaults_llm_pricing.example.yaml` is generated from the compiled-in table
|
||||
(`go generate ./management/internals/modules/agentnetwork/pricing`) and
|
||||
golden-tested, so operators start from a file matching the built-in rates exactly.
|
||||
|
||||
### Budget rule resolution (min-wins, group+user bound)
|
||||
|
||||
```mermaid
|
||||
@@ -124,7 +208,7 @@ At request time the path is independent: the proxy calls `SelectPolicyForRequest
|
||||
| on_request | 3 | `llm_identity_inject` | `{"providers":[{provider_id, header_pair?, json_metadata?, extra_headers?}]}` | **true** |
|
||||
| on_request | 4 | `llm_guardrail` | `{"provider_allowlists"?: {providerID: []model}, "prompt_capture":{enabled,redact_pii}}` | – |
|
||||
| on_response | 5 | `llm_limit_record` | `{}` (runs LAST at runtime) | – |
|
||||
| on_response | 6 | `cost_meter` | `{}` | – |
|
||||
| on_response | 6 | `cost_meter` | `{"pricing":{"defaults":{surface:{model:rates}},"providers"?:{providerRecordID:{model:rates}}}}` — rates are `{input_per_1k, output_per_1k, cached_input_per_1k?, cache_read_per_1k?, cache_creation_per_1k?}` | – |
|
||||
| on_response | 7 | `llm_response_parser` | `{"capture_completion": <bool>, "redact_pii"?: true}` | – |
|
||||
- **Synthesized service shape** (`synthesizer.go:739`): `Mode=HTTP`, `Private=true`, `Domain=<subdomain>.<cluster>`, `AccessGroups=unionSourceGroups(enabledPolicies)`, one `TargetTypeCluster` target with `Host=noop.invalid:443` (router rewrites per request), `Options.{DirectUpstream,AgentNetwork}=true`, `DisableAccessLog=!settings.EnableLogCollection`, `CaptureMax{Req,Resp}Bytes=1<<20`, `CaptureContentTypes=["application/json","text/event-stream"]`.
|
||||
|
||||
@@ -139,6 +223,12 @@ At request time the path is independent: the proxy calls `SelectPolicyForRequest
|
||||
- **Orphan providers (no enabled policy authorises them) NEVER reach the router** (`synthesizer.go:351-357`); skipped from `identity_inject` for symmetry.
|
||||
- **Provider creation refuses empty `api_key`** (`manager.go:175`); **deletion refuses while any policy still references it** (`manager.go:265-273`).
|
||||
- **Session keypair stability across provider edits** (`manager.go:226-228`) — server-managed, copied through every `UpdateProvider`, never API-surfaced.
|
||||
- **Management is the sole pricing authority.** The proxy has no embedded price list, so an account whose `cost_meter` config carries no `pricing` block bills **nothing** (`cost.skipped=unknown_model`, $0) rather than falling back to stale built-ins. The top-level `pricing` wrapper is also the feature-detection signal in both directions: an old proxy ignores it as an unknown field, and a new proxy reads its absence as "old management".
|
||||
- **Per-provider prices are materialized at synth time, not merged on the proxy** (`synthesizer_pricing.go:114-131`). A per-record entry is always complete, so the proxy's lookup is per-record-then-defaults with no field-level fallback between tiers.
|
||||
- **An explicit operator price of `0` prices the model as free** — it must not be treated as "unset" and reverted to list price (`synthesizer_pricing.go:49-54`). Only *cache*-rate fields distinguish unset from zero, via `*float64`.
|
||||
- **Pricing model ids are normalized with the same functions the request parser uses** (`normalizePricingModelID`). If the two ever diverge, per-record prices silently stop matching and every request falls through to surface defaults.
|
||||
- **The default table's coverage is structural, not curated.** It is derived from the catalog via each provider's `PricingSurfaces`; `TestDefaultTable_CoversEveryCatalogModel` fails on an unpriced catalog model and `TestDefaultTable_NoConflictingContributions` fails if two providers contribute the same (surface, model) at different rates.
|
||||
- **A pricing-defaults file failure is fatal only at startup, and only for an explicitly configured path.** Runtime reload failures keep the previous table; a deleted file reverts to compiled-in defaults (`pricing/override.go:62-81, 113-148`).
|
||||
|
||||
## Things to scrutinize
|
||||
|
||||
@@ -176,10 +266,12 @@ At request time the path is independent: the proxy calls `SelectPolicyForRequest
|
||||
- **Capture-pointer semantics (restated):** non-agent-network callers see no field → legacy nil-default emit, identical to pre-PR. Agent-network targets always carry an explicit `capture_*` value.
|
||||
- **`TestSynthesizeServices_HappyPath` was updated:** request-parser config moved from `{}` to `{"capture_prompt":false}` (`synthesizer_test.go:174`). External snapshot tests against synth output need updating.
|
||||
- **`MergedGuardrails` retains zeroed `TokenLimits`/`Budget`/`Retention`** even though `Policy.Limits` carries the real values now; `llm_limit_check` is the authoritative enforcement. Comment at `synthesizer.go:940-948` calls this out.
|
||||
- **`cost_meter`'s `pricing` block is version-skew-safe in both directions.** A proxy predating config-delivered pricing ignores the field as unknown JSON (it previously priced from its own embedded table, so it keeps billing — at its own rates, which is the skew to be aware of during a rolling upgrade). A current proxy paired with old management sees no `pricing` block, logs one warning at chain-build time, and records `cost.skipped=unknown_model` — token counting and cap enforcement are unaffected, only the USD annotation goes to $0.
|
||||
|
||||
### Performance
|
||||
|
||||
- **`SynthesizeServices` runs on every controller tick / mutation reconcile.** Cost: 4 store reads + optional per-provider keypair backfill. Sort + index + merge are O(N log N) / O(P × G); dominant cost is JSON marshalling. No nested loops escape these dimensions.
|
||||
- **The full default pricing table is marshalled into every account's `cost_meter` config on every synth** (~10 KB serialized). This is a deliberate trade: it keeps gateway-style providers priced for every catalog model, and it is the largest single contributor to the synth JSON. `DefaultTable()` itself is a pointer load (or a `sync.Once`-built map) — the cost is the marshal, not the build.
|
||||
- **`reconcile.diffMappings` is O(N + M)** with N=M=1 per account today — effectively constant.
|
||||
- **`SynthesizeServicesForCluster`** (`synthesizer.go:71`) walks every account on a cluster; per-account failures are **swallowed** (`synthesizer.go:91-93`) so a single misconfigured account doesn't drop the cluster. Runs per proxy reconnect.
|
||||
|
||||
@@ -188,6 +280,7 @@ At request time the path is independent: the proxy calls `SelectPolicyForRequest
|
||||
- **Activity codes:** `AgentNetwork{Provider,Policy,Guardrail,BudgetRule}{Created,Updated,Deleted}`; `AgentNetworkSettingsUpdated` with `log_collection/prompt_collection/redact_pii` payload (`manager.go:567-571`). **No activity code for `SelectPolicyForRequest` denies** — surfaced via proxy access log only (likely intentional given volume).
|
||||
- **Deny codes** namespaced: `llm_policy.{token,budget}_cap_exceeded`, `llm_account.{token,budget}_cap_exceeded` (`policyselect.go:18-26`).
|
||||
- **Reconcile failures are logged at warn and swallowed** (`reconcile.go:42-44`). Persistent synth failures (e.g. unknown catalog id) silently keep the proxy out of sync — consider a manager-level synth-health surface if this becomes a support burden.
|
||||
- **Pricing-file lifecycle logs at info** (load, reload, revert-to-built-ins) and **at warn** for a runtime reload failure; the mtime check itself is `Debugf`. There is no metric on reload failures, so an operator who breaks the file mid-flight keeps billing at the previous table with only a log line to show it (`pricing/override.go:113-148`).
|
||||
|
||||
## Test coverage
|
||||
|
||||
@@ -198,6 +291,9 @@ At request time the path is independent: the proxy calls `SelectPolicyForRequest
|
||||
| `synthesizer_guardrail_realstore_test.go` | `PromptCaptureAccountIsSoleControl`; `PromptCaptureFlowsWhenAccountOptsIn`; `AccountRedactWithoutGuardrailRedact`; `NoGuardrail_CaptureOff`. |
|
||||
| `synthesizer_log_collection_realstore_test.go` | `LogCollection{Off_SuppressesAccessLog,On_PermitsAccessLog}` — verifies `DisableAccessLog` propagation through `ToProtoMapping`. |
|
||||
| `synthesizer_parser_redact_realstore_test.go` | **Capture-pointer regression suite:** `ParserConfigsCarryRedactPii`; `ParserConfigsSuppressCaptureWhenLogCollectionOnly` (log=on/prompt=off ⇒ both capture flags false); `ParserConfigsOmitRedactPiiWhenOff`. |
|
||||
| `synthesizer_pricing_test.go` | `BuildCostMeterConfig_{BedrockModelNormalization,CacheRateNilVsZero,OrphanAndGatewayProviders}` — the per-record tier's three load-bearing rules: keys normalized like the parser's, `nil` cache pointer inherits vs explicit `0` bills at input rate, and orphan / gateway (empty `Models`) providers ship no per-record entry. |
|
||||
| `pricing/defaults_test.go` | `DefaultTable_{CoversEveryCatalogModel,NoConflictingContributions,AllRatesFiniteNonNegative,PinnedRates}`; `LookupDefault_SurfaceOrder`. Catalog-derived coverage + rate sanity are structural, not curated. |
|
||||
| `pricing/override_test.go` | `LoadFile_{MergesOverCompiledDefaults,MissingPath,RejectsInvalid}`; `Reload_LifeCycle` (mtime detect, parse error keeps previous, delete reverts to built-ins); `ExampleYAML_InSyncWithBuiltins` golden. |
|
||||
| `policyselect_test.go` | Mock-store: `NoApplicablePolicies`; `AllowWithLowestGroupAttribution`; `LargerPoolWinsAcrossUsageLevels`; `StaysOnLargerPoolAfterPartialDrain`; `FallsThroughToSmallerPoolWhenLargerExhausted`; `TiebreakBy{LargerGroupPool,CreatedAt}`; `DeniesWhenAllExhausted`; `UncappedPolicyAlwaysWinsAgainstCapped`; `DisabledPolicyIgnored`; `StoreErrorPropagates`; `RejectsEmptyAccount`; `SharesGroupCounterAcrossPolicies`; `AntiFallThroughOnLowestGroup`; `BudgetOnlyExhaustionDenies`; `BudgetTighterThanTokenWins`. |
|
||||
| `policyselect_realstore_test.go` | Real-sqlite regression guard: `NoApplicablePolicies`; `AllowAndLowestGroupAttribution`; `LargerPoolWins_FallsThroughWhenExhausted`; `BudgetCapDenies`; `GroupCounterSharedAcrossPolicies`; `DisabledPolicyIgnored`. |
|
||||
| `policyselect_account_realstore_test.go` | Account budget rules: `AccountCeilingBindsEvenWithUncappedPolicy` (min-wins); `AccountGroupCeiling`; `AccountTargetUsersBindsOnlyThatUser`; `AccountRuleRecordsToOwnWindow`. |
|
||||
|
||||
@@ -5,7 +5,7 @@ LLM request. The two highest-blast-radius areas are the **capture-pointer
|
||||
semantics** and the **limit_check ⇒ limit_record** record-once invariant.
|
||||
|
||||
Sibling module: [32-proxy-llm-parsers.md](./32-proxy-llm-parsers.md) — the SDK
|
||||
adapters + pricing catalog this chain delegates to.
|
||||
adapters + pricing table and cost formula this chain delegates to.
|
||||
|
||||
---
|
||||
|
||||
@@ -34,7 +34,7 @@ rewrites.
|
||||
| `llm_identity_inject` | OnRequest | `llm.{resolved_provider_id,authorising_groups}`, `Input.{UserEmail,UserID,UserGroups,UserGroupNames}` | none | header strip/inject + optional body rewrite |
|
||||
| `llm_guardrail` | OnRequest | `llm.{model,request_prompt_raw}` | `llm_policy.{decision,reason}`, `llm.request_prompt` | none (model allowlist deny) |
|
||||
| `llm_response_parser` | OnResponse | `llm.provider`, `Input.{RespHeaders,RespBody,Status}` | `llm.{input,output,total,cached_input,cache_creation}_tokens`, `llm.response_completion` | none |
|
||||
| `cost_meter` | OnResponse | `llm.{provider,model}`, token buckets | `cost.usd_total` or `cost.skipped` | pricing lookup |
|
||||
| `cost_meter` | OnResponse | `llm.{provider,model,resolved_provider_id}`, token buckets | `cost.usd_{input,cached_input,cache_creation,output,total,cache}` or `cost.skipped` | none (in-memory pricing lookup) |
|
||||
| `llm_limit_record` | OnResponse | `llm.{attribution_group_id,attribution_window_seconds,input_tokens,output_tokens}`, `cost.usd_total` | none | gRPC `RecordLLMUsage` |
|
||||
|
||||
[all_test.go:26–40](../../../proxy/internal/middleware/builtin/all_test.go)
|
||||
@@ -44,7 +44,7 @@ locks the ID set; adding or removing one is a conscious extension.
|
||||
|
||||
| File | LOC | Notes |
|
||||
|---|---:|---|
|
||||
| `builtin.go` | 86 | Registry + `FactoryContext` (ctx, data dir, meter, logger, mgmt client) |
|
||||
| `builtin.go` | 90 | Registry + `FactoryContext` (ctx, meter, logger, mgmt client) |
|
||||
| `all_test.go` | 41 | Locks the 8-ID registry surface |
|
||||
| `agentnetwork_chain_integration_test.go` | 319 | Live sqlite + real gRPC bufconn; gate→recorder wire path |
|
||||
| `llm_request_parser/*` | 162 / 66 / 356 | Provider detection, body parse, prompt extraction with capture-pointer gating |
|
||||
@@ -53,7 +53,7 @@ locks the ID set; adding or removing one is a conscious extension.
|
||||
| `llm_identity_inject/*` | 440 / 108 / 666 | HeaderPair (LiteLLM) + JSONMetadata (Portkey) + ExtraHeaders |
|
||||
| `llm_guardrail/*` | 176 / 82 / 75 / 219 / 217 | Model allowlist + optional prompt capture with PII redaction |
|
||||
| `llm_response_parser/*` | 258 / 222 / 43 / 433 / 169 / 111 | Buffered + SSE accumulation; AWS event-stream accumulator (`streaming_bedrock.go`) for Bedrock; capture-pointer gates completion emit |
|
||||
| `cost_meter/*` | 181 / 84 / 439 | Token → USD via `proxy/internal/llm/pricing` |
|
||||
| `cost_meter/*` | 236 / 98 / 586 | Token → USD via `proxy/internal/llm/pricing`; both pricing tiers arrive in the middleware config |
|
||||
| `llm_limit_record/*` | 144 / 35 / 191 | Post-flight `RecordLLMUsage` (5s, debug-on-error) |
|
||||
|
||||
## Per-middleware
|
||||
@@ -168,12 +168,46 @@ token schema.
|
||||
|
||||
### cost_meter
|
||||
|
||||
Reads `llm.provider` + `llm.model` + token buckets, looks up per-1k rate via
|
||||
`pricing.Loader`, emits `cost.usd_total` or a closed-set `cost.skipped`
|
||||
reason (`missing_provider/model/tokens`, `unparseable_tokens`, `zero_tokens`,
|
||||
`unknown_model`). Loader's hot-reload goroutine is bound to proxy-lifetime
|
||||
context via `startReloader`. **Key invariant:** provider-shape switch lives
|
||||
in `pricing.Table.Cost` (sibling doc) — `cost_meter` stays provider-agnostic.
|
||||
Reads `llm.provider` + `llm.model` + token buckets, looks up the per-1k rates,
|
||||
and emits the full `cost.usd_*` breakdown (four per-bucket values plus the
|
||||
`_total` and `_cache` aggregates) or a closed-set `cost.skipped` reason
|
||||
(`missing_provider/model/tokens`, `unparseable_tokens`, `zero_tokens`,
|
||||
`unknown_model`).
|
||||
|
||||
**Management owns pricing.** The proxy carries no embedded price list: the whole
|
||||
table arrives in this middleware's `ConfigJSON` as
|
||||
`{pricing: {defaults, providers}}`, synthesized by management from the catalog
|
||||
plus the operator's stored per-provider prices
|
||||
([factory.go:13–34](../../../proxy/internal/middleware/builtin/cost_meter/factory.go)).
|
||||
Both tiers are validated by `pricing.NewTable` / `pricing.NewEntries` at
|
||||
construction, so a non-finite or negative rate fails the chain build. A price
|
||||
change is an ordinary mapping push — the chain rebuild yields a fresh instance
|
||||
over a fresh immutable table, so there is no data dir, no pricing file, no
|
||||
reload goroutine, and nothing to invalidate.
|
||||
|
||||
**Two-tier lookup**
|
||||
([middleware.go:165–183](../../../proxy/internal/middleware/builtin/cost_meter/middleware.go)):
|
||||
|
||||
1. **Per-provider-record** — the operator's stored price for the route that
|
||||
actually served the request, keyed by the `llm.resolved_provider_id` that
|
||||
`llm_router` stamped on the allow path, then by normalized model id. Entries
|
||||
arrive fully materialized (management folds default cache rates in at synth
|
||||
time), so there is no merging here. Absent metadata — no router in the chain
|
||||
— skips this tier.
|
||||
2. **Surface defaults** — the catalog-derived table keyed by `llm.provider`
|
||||
(`openai`/`anthropic`/`bedrock`). This is also what prices gateway-style
|
||||
providers, which enumerate no models and therefore get no per-record entry.
|
||||
|
||||
**Backward compatibility:** a config with no `pricing` block means management
|
||||
predates config-delivered pricing. The factory logs one warning at build time
|
||||
and the instance records `cost.skipped=unknown_model` ($0) for every request
|
||||
rather than falling back to a stale built-in price list
|
||||
([factory.go:55–60](../../../proxy/internal/middleware/builtin/cost_meter/factory.go)).
|
||||
|
||||
**Key invariant:** the provider-shape switch lives in `pricing.EntryCosts`
|
||||
(sibling doc) and is selected by the **surface**, not by which tier the entry
|
||||
came from — `cost_meter` stays provider-agnostic, and a per-record override on
|
||||
an Anthropic route still bills its cache buckets additively.
|
||||
|
||||
### llm_limit_record
|
||||
|
||||
@@ -246,12 +280,14 @@ no mocks. Tests: `TestChain_AllowPath_StampsAttributionAndRecordsCounter`
|
||||
| `llm_identity_inject` | `{providers: [{provider_id, header_pair?|json_metadata?, extra_headers?}]}` |
|
||||
| `llm_guardrail` | `{provider_allowlists: {providerID: []string}, prompt_capture: {enabled, redact_pii}}` — allowlist keyed by resolved provider id; a provider absent from the map is unrestricted (fail-closed backstop; authoritative per-policy/group check is management's `CheckLLMPolicyLimits`) |
|
||||
| `llm_response_parser` | `{redact_pii?, capture_completion?: *bool}` |
|
||||
| `cost_meter` | `{pricing_path?}` (basename inside data-dir; defaults `pricing.yaml`) |
|
||||
| `cost_meter` | `{pricing: {defaults: {surface: {model: rates}}, providers: {providerRecordID: {model: rates}}}}` — rates are `{input_per_1k, output_per_1k, cached_input_per_1k?, cache_read_per_1k?, cache_creation_per_1k?}`. A missing `pricing` key means "management predates config-delivered pricing": every request records `cost.skipped=unknown_model` |
|
||||
| `llm_limit_record` | `{}` — same pattern as `llm_limit_check` |
|
||||
|
||||
All factories accept empty / null / `{}` / whitespace as zero-value config;
|
||||
only structurally invalid JSON is rejected so misconfig surfaces at chain
|
||||
build time.
|
||||
build time. `cost_meter` adds a semantic check on top of that: a `pricing`
|
||||
block carrying a negative or non-finite rate fails the build too, rather than
|
||||
mispricing live traffic.
|
||||
|
||||
## Invariants
|
||||
|
||||
@@ -320,10 +356,11 @@ non-object `metadata` field
|
||||
— header path still attributes, but body-level tag-budget enforcement
|
||||
doesn't run for that request.
|
||||
|
||||
**Concurrency.** `cost_meter` shares a `pricing.Loader` via
|
||||
`atomic.Pointer[Table]`; readers always see a consistent table. Every
|
||||
middleware is a stateless value receiver. Integration test uses real bufconn
|
||||
gRPC — race detector is the meaningful bar.
|
||||
**Concurrency.** `cost_meter`'s two pricing tables are built once from the
|
||||
middleware config and never mutated, so the lookup path needs no lock or atomic
|
||||
swap — a price change replaces the whole instance. Every middleware is
|
||||
otherwise a stateless value receiver. Integration test uses real bufconn gRPC —
|
||||
race detector is the meaningful bar.
|
||||
|
||||
**Perf.** Hot path is `lookupKV` linear scan over <10 KVs; `cost_meter.Cost`
|
||||
is O(1); SSE accumulation is single-pass. No map allocation per call.
|
||||
@@ -349,13 +386,13 @@ counter accuracy.
|
||||
| `llm_guardrail/redact_test.go` | 15 | Email, SSN, phone (E.164 + NA), bearer, IPv4; fixture-driven |
|
||||
| `llm_response_parser/middleware_test.go` | 18 | Buffered OAI+Anthro, capture-pointer, redact, truncation |
|
||||
| `llm_response_parser/streaming_test.go` | 7 | OAI usage frame, Anthro message_delta, truncated body best-effort |
|
||||
| `cost_meter/middleware_test.go` | 17 | Each skip reason, provider-shape, pricing loader integration |
|
||||
| `cost_meter/middleware_test.go` | 22 | Each skip reason, provider-shape formulas, config-delivered defaults, per-record-beats-defaults + miss-falls-back, per-record uses surface formula, nil-pricing skips everything, invalid-rate rejection |
|
||||
| `llm_limit_record/middleware_test.go` | 7 | Skip-on-no-signal, skip-on-missing-attribution, RPC failure swallowed |
|
||||
|
||||
## Cross-references
|
||||
|
||||
- Sibling: [32-proxy-llm-parsers.md](./32-proxy-llm-parsers.md) — SDK adapters
|
||||
+ SSE framer + pricing loader.
|
||||
+ SSE framer + pricing table and cost formula.
|
||||
- Path-routed providers (Vertex AI + Bedrock), `keyfile::` credential, GCP
|
||||
token minting, `/bedrock` prefix:
|
||||
[50-path-routed-providers.md](./50-path-routed-providers.md).
|
||||
|
||||
@@ -9,7 +9,7 @@ pricing table's per-provider cost formula is the highest-leverage place a
|
||||
small bug would silently mis-bill operators.
|
||||
|
||||
Sibling module: [31-proxy-middleware-builtin.md](./31-proxy-middleware-builtin.md)
|
||||
— the 8 middlewares that consume this package's parsers + pricing loader.
|
||||
— the 8 middlewares that consume this package's parsers + pricing table.
|
||||
|
||||
---
|
||||
|
||||
@@ -24,8 +24,9 @@ proxy-framework dependencies:
|
||||
- `openai.go` / `anthropic.go` / `bedrock.go` — per-provider `Parser` impls.
|
||||
- `sse.go` — SSE scanner (`Scanner`, `Event`, `NewScanner`).
|
||||
- `errors.go` — sentinels callers branch on with `errors.Is`.
|
||||
- `pricing/` — embedded-default + hot-reload override table with
|
||||
symlink-safe Unix loader (build-tagged stub elsewhere).
|
||||
- `pricing/` — immutable pricing table + the per-surface cost formula. The
|
||||
rates themselves come from management inside `cost_meter`'s middleware
|
||||
config; this package holds no price list and reads no files.
|
||||
- `fixtures/` — captured request/response/stream bodies the tests replay.
|
||||
|
||||
The package carries zero proxy-framework dependencies so the same parsers can
|
||||
@@ -47,12 +48,9 @@ be reused later by a WASM adapter
|
||||
| `sse_test.go` | 175 | 12 tests; fixture replay + multiline + size limits |
|
||||
| `parser_test.go` | 53 | `Parsers()`, `DetectParser`, provider enum values |
|
||||
| `errors.go` | 31 | 6 sentinels: `Err{Unknown,Unsupported}Provider/Model`, `Err{NotLLM,Malformed}Response`, `ErrStreamingUnsupported`, `ErrMalformedRequest` |
|
||||
| `pricing/pricing.go` | 421 | `Loader`, `Table`, `Entry`; embedded defaults + atomic swap + mtime reload |
|
||||
| `pricing/pricing_unix.go` | 69 | `O_NOFOLLOW` + fstat-from-FD + 1 MiB cap |
|
||||
| `pricing/pricing_other.go` | 21 | Stub returning "not supported on this platform" |
|
||||
| `pricing/pricing_test.go` | 432 | 21 tests — symlink rejection, reload race, path traversal, oversize |
|
||||
| `pricing/defaults_pricing.yaml` | 85 | go:embed source of truth |
|
||||
| `fixtures/*` | 21–59 | OAI chat/responses/stream + Anthro messages/stream + pricing starter |
|
||||
| `pricing/pricing.go` | 234 | `Table`, `Entry`, `EntryJSON`, `Costs`; `NewTable`/`NewEntries` validation + `EntryCosts` formula. No I/O, no reload, no embedded rates |
|
||||
| `pricing/pricing_test.go` | 177 | 10 tests — provider-shape formulas, cached clamp, rate fallback, nil-safety, rate validation |
|
||||
| `fixtures/*` | 21–59 | OAI chat/responses/stream + Anthro messages/stream |
|
||||
|
||||
## Request body → parser dispatch
|
||||
|
||||
@@ -188,9 +186,11 @@ response leg, covering both Bedrock body shapes:
|
||||
`totalTokens`). `firstNonZero` folds the two naming conventions into one
|
||||
`Usage`; when Converse omits `totalTokens` the parser sums the buckets.
|
||||
|
||||
`ProviderName()` returns `"bedrock"` — its own `defaults_pricing.yaml` block,
|
||||
keyed by the **normalised** model id (region prefix + version suffix stripped by
|
||||
the request parser). `ParseResponse` returns `ErrStreamingUnsupported` for an
|
||||
`ProviderName()` returns `"bedrock"` — its own pricing surface in the table
|
||||
management ships, keyed by the **normalised** model id (region prefix + version
|
||||
suffix stripped by the request parser; management normalises its keys the same
|
||||
way at synth time so the two compare equal). `ParseResponse` returns
|
||||
`ErrStreamingUnsupported` for an
|
||||
AWS binary event-stream content-type (`application/vnd.amazon.eventstream`,
|
||||
`isAWSEventStream`) so the caller routes to the streaming accumulator instead.
|
||||
|
||||
@@ -205,11 +205,34 @@ response body. Streaming accumulators live in the middleware package
|
||||
([llm_response_parser/streaming.go](../../../proxy/internal/middleware/builtin/llm_response_parser/streaming.go))
|
||||
but use `llm.NewScanner` so the framing contract stays here.
|
||||
|
||||
### Pricing catalog
|
||||
### Pricing table
|
||||
|
||||
`Table.Cost`
|
||||
([pricing.go:129–174](../../../proxy/internal/llm/pricing/pricing.go))
|
||||
is the cost formula — most security-relevant math in this module:
|
||||
**Management is the sole pricing authority.** The proxy carries no embedded
|
||||
price list and reads no pricing file: the whole table arrives inside
|
||||
`cost_meter`'s `ConfigJSON` on the ordinary mapping push, and a price change
|
||||
is just another push — the chain rebuild constructs a fresh `Table`, so there
|
||||
is nothing to reload
|
||||
([pricing.go:1–7](../../../proxy/internal/llm/pricing/pricing.go)). The
|
||||
management side of the contract (catalog defaults, the operator's stored
|
||||
per-provider prices, and `AgentNetwork.PricingDefaultsFile`) is covered in the
|
||||
management-side module guide; `cost_meter`'s wire shape is in
|
||||
[31-proxy-middleware-builtin.md](./31-proxy-middleware-builtin.md).
|
||||
|
||||
`EntryJSON`
|
||||
([pricing.go:36–45](../../../proxy/internal/llm/pricing/pricing.go)) is the
|
||||
management→proxy contract — five USD-per-1k rates under `input_per_1k`,
|
||||
`output_per_1k`, `cached_input_per_1k`, `cache_read_per_1k`,
|
||||
`cache_creation_per_1k`. Management's `pricing.Entry` marshals the identical
|
||||
names, and `EntryJSON`/`Entry` are field-identical so `NewEntries` converts by
|
||||
direct struct conversion rather than field-by-field copying (a new rate can't
|
||||
be silently dropped in transit).
|
||||
|
||||
`EntryCosts`
|
||||
([pricing.go:183–234](../../../proxy/internal/llm/pricing/pricing.go))
|
||||
is the cost formula — most security-relevant math in this module. The
|
||||
**surface** (the `llm.provider` value the request parser stamped) selects the
|
||||
formula, never the tier the entry came from: a per-provider-record override on
|
||||
an Anthropic route still bills its cache buckets additively.
|
||||
|
||||
| Provider | Formula |
|
||||
|---|---|
|
||||
@@ -218,7 +241,7 @@ is the cost formula — most security-relevant math in this module:
|
||||
| default | `inTokens × InputPer1K + outTokens × OutputPer1K` |
|
||||
|
||||
`bedrock` shares the Anthropic additive-cache formula
|
||||
([pricing.go:172-174](../../../proxy/internal/llm/pricing/pricing.go)):
|
||||
([pricing.go:214–229](../../../proxy/internal/llm/pricing/pricing.go)):
|
||||
Anthropic-on-Bedrock reports the same additive cache buckets, while non-Anthropic
|
||||
Bedrock models (Nova, Llama) simply report zero in those buckets so cost reduces
|
||||
to `input + output`.
|
||||
@@ -226,15 +249,12 @@ to `input + output`.
|
||||
Each per-bucket rate falls back to `InputPer1K` when zero — operators opt in
|
||||
to discounts by setting the field.
|
||||
|
||||
`Loader`
|
||||
([pricing.go:212–268](../../../proxy/internal/llm/pricing/pricing.go))
|
||||
overlays an optional `pricing.yaml` from data-dir on top of the go:embed
|
||||
defaults. Atomic pointer swap means readers never observe a partial update.
|
||||
The mtime-poll reloader (30s default cadence) keeps the previous table on
|
||||
parse failure so cost annotation never goes blank during a botched edit.
|
||||
|
||||
`defaults_pricing.yaml` is the source of truth for built-in pricing.
|
||||
Operator overrides only carry the entries they want to change.
|
||||
`Costs`
|
||||
([pricing.go:143–163](../../../proxy/internal/llm/pricing/pricing.go)) is the
|
||||
per-request split. The four per-bucket fields are the base; `TotalUSD` and
|
||||
`CacheUSD` are **derived** in `newCosts` so the aggregates can never drift from
|
||||
the breakdown. `InputUSD` is always the non-cached input bucket on both
|
||||
provider shapes, so input and cached-input never double-count.
|
||||
|
||||
## Public contracts
|
||||
|
||||
@@ -264,29 +284,38 @@ Order matters: `DetectFromURL` ties resolve by registration order.
|
||||
`ProviderBedrock = 3`. Numeric values are persisted in nothing today but treat
|
||||
them as wire-stable — new providers must take fresh numbers.
|
||||
|
||||
**`Pricing` lookup**
|
||||
([pricing.go:129](../../../proxy/internal/llm/pricing/pricing.go)):
|
||||
**`Pricing` construction + lookup**
|
||||
([pricing.go:60–130](../../../proxy/internal/llm/pricing/pricing.go)):
|
||||
|
||||
```go
|
||||
func NewEntries(raw map[string]map[string]EntryJSON) (map[string]map[string]Entry, error)
|
||||
func NewTable(raw map[string]map[string]EntryJSON) (*Table, error)
|
||||
|
||||
func (t *Table) Lookup(provider, model string) (Entry, bool)
|
||||
func (t *Table) Cost(provider, model string, inTokens, outTokens, cachedInput, cacheCreation int64) (float64, bool)
|
||||
func (t *Table) Costs(provider, model string, inTokens, outTokens, cachedInput, cacheCreation int64) (Costs, bool)
|
||||
func EntryCosts(entry Entry, surface string, inTokens, outTokens, cachedInput, cacheCreation int64) Costs
|
||||
```
|
||||
|
||||
Nil-safe: `t.Cost` on a nil receiver returns `(0, false)`
|
||||
([pricing.go:130–132](../../../proxy/internal/llm/pricing/pricing.go)).
|
||||
`ok=false` means provider or model is absent from the loaded table; the caller
|
||||
emits `cost.skipped=unknown_model`.
|
||||
`NewTable` is the surface-keyed defaults table; `NewEntries` returns the raw
|
||||
two-level map `cost_meter` uses for the per-provider-record tier (it looks up an
|
||||
`Entry` directly and calls `EntryCosts`, so it needs no `Table` wrapper). Both
|
||||
reject any non-finite or negative rate, so a corrupt config fails the chain
|
||||
build rather than mispricing silently. Nil input yields an empty,
|
||||
never-matching table.
|
||||
|
||||
Nil-safe: `t.Cost`/`t.Lookup` on a nil receiver returns `ok=false`
|
||||
([pricing.go:96–99](../../../proxy/internal/llm/pricing/pricing.go)).
|
||||
`ok=false` means the surface or model is absent from the table management sent;
|
||||
the caller emits `cost.skipped=unknown_model`.
|
||||
|
||||
## Invariants
|
||||
|
||||
1. **Cross-platform pricing build.** `pricing_unix.go` carries the only
|
||||
functional `loadPricing` (uses `syscall.O_NOFOLLOW` and `f.Stat()` on an
|
||||
open descriptor — both Unix-only). `pricing_other.go` is a build-tag
|
||||
fallback that returns `"not supported on this platform"`
|
||||
([pricing_other.go:14–16](../../../proxy/internal/llm/pricing/pricing_other.go)).
|
||||
The proxy is Linux-only in production today; a Windows port needs an
|
||||
equivalent path-as-handle implementation. Reviewers building on Windows
|
||||
should expect this surface to return an error at startup if an override
|
||||
file is configured.
|
||||
1. **The pricing package is pure and platform-independent.** No file I/O, no
|
||||
`//go:embed`, no goroutines, no build tags — the rates arrive as config, so
|
||||
there is nothing platform-specific left to port. Anything reintroducing a
|
||||
read-from-disk path here re-splits pricing authority between management and
|
||||
the proxy, which is exactly what this design removed.
|
||||
|
||||
2. **SSE scanner handles partial chunks.** A buffered prefix that doesn't end
|
||||
in `\n\n` still yields its accumulated event before `io.EOF`
|
||||
@@ -298,38 +327,45 @@ emits `cost.skipped=unknown_model`.
|
||||
usage rather than aborting
|
||||
([streaming.go:68–73, 144–150](../../../proxy/internal/middleware/builtin/llm_response_parser/streaming.go)).
|
||||
|
||||
3. **`defaults_pricing.yaml` is the source of truth.** Compiled into the
|
||||
binary via `//go:embed`
|
||||
([pricing.go:29–30](../../../proxy/internal/llm/pricing/pricing.go)).
|
||||
`DefaultTable()` parses once and panics on parse failure
|
||||
([pricing.go:42–49](../../../proxy/internal/llm/pricing/pricing.go))
|
||||
— by design: a broken embedded YAML must not ship to production.
|
||||
3. **Management is the only source of rates.** `Table` has no constructor that
|
||||
invents prices: the only way in is `NewTable`/`NewEntries` over the wire map
|
||||
management sent. A missing or empty `pricing` block therefore means *no
|
||||
prices at all* (`cost_meter` records `cost.skipped=unknown_model`, $0) —
|
||||
never a stale built-in fallback that would silently bill list price.
|
||||
|
||||
4. **Loader path validation.** `resolveMiddlewareDataPath`
|
||||
([pricing.go:370–394](../../../proxy/internal/llm/pricing/pricing.go))
|
||||
rejects absolute paths, traversal segments, and basenames that fail
|
||||
`basenameRegex = ^[a-zA-Z0-9._-]+$`. The resolved path must remain
|
||||
inside `baseDir` even after `filepath.Clean`. Tests:
|
||||
`TestNewLoader_PathValidation`, `TestNewLoader_PathValidation_Extended`,
|
||||
`TestNewLoader_SymlinkOutsideBaseDirRejected`, `TestNewLoader_SymlinkRejected`.
|
||||
4. **Tables are immutable once built.** `Table.entries` is written only in
|
||||
`NewEntries` and never mutated afterwards, and `cost_meter`'s `perRecord`
|
||||
map is likewise build-time-only
|
||||
([pricing.go:47–52](../../../proxy/internal/llm/pricing/pricing.go)). This
|
||||
is what makes the no-reload design safe: a price change arrives as a mapping
|
||||
push that builds a new middleware instance over a new table, so concurrent
|
||||
readers can't observe a half-updated price list and no atomic swap or lock
|
||||
is needed on the hot path.
|
||||
|
||||
5. **Unix loader symlink safety.** `O_NOFOLLOW` on open, `f.Stat()` on the
|
||||
open descriptor (never re-stat by path), `info.Mode().IsRegular()` check,
|
||||
`io.LimitReader(f, maxPricingBytes+1)` with a final size assertion
|
||||
([pricing_unix.go:25–57](../../../proxy/internal/llm/pricing/pricing_unix.go)).
|
||||
A mid-read symlink swap is detected because the fstat is on the original
|
||||
fd. Test: `TestNewLoader_RejectsOversizedFile_FixesM4`.
|
||||
5. **Rate validation happens at chain-build time, not per request.**
|
||||
`NewEntries` rejects negative, NaN, and ±Inf rates field by field
|
||||
([pricing.go:60–83](../../../proxy/internal/llm/pricing/pricing.go)), naming
|
||||
the offending surface/model/field in the error. Management enforces the same
|
||||
constraints at its API boundary and in its YAML parser, so this is
|
||||
defense-in-depth — but it means a corrupt push fails loudly at build instead
|
||||
of producing negative costs on live traffic. Test:
|
||||
`TestNewTable_ValidatesRates`.
|
||||
|
||||
6. **`yaml.NewDecoder(...).KnownFields(true)`**
|
||||
([pricing.go:397–398](../../../proxy/internal/llm/pricing/pricing.go))
|
||||
rejects YAML files that carry fields not in the schema. A typo in an
|
||||
operator override file fails loud instead of silently zeroing rates.
|
||||
6. **New rates must be added to `Entry`, `EntryJSON`, *and* management's
|
||||
`pricing.Entry` together.** `NewEntries` converts by direct struct
|
||||
conversion `Entry(e)`
|
||||
([pricing.go:76–78](../../../proxy/internal/llm/pricing/pricing.go)), which
|
||||
only compiles while the two structs stay field-identical — so the proxy half
|
||||
is compiler-enforced. The management half is not: a rate added there but not
|
||||
here unmarshals into nothing and prices that bucket at `InputPer1K`.
|
||||
|
||||
## Things to scrutinise
|
||||
|
||||
**Correctness.** Verify OpenAI cached-prompt clamp at
|
||||
[pricing.go:147–149](../../../proxy/internal/llm/pricing/pricing.go)
|
||||
short-circuits before subtraction. `Anthropic.TotalTokens` sums all four
|
||||
**Correctness.** Verify the OpenAI cached-prompt clamp at
|
||||
[pricing.go:203–206](../../../proxy/internal/llm/pricing/pricing.go)
|
||||
short-circuits before subtraction. Negative token counts are clamped to zero up
|
||||
front ([pricing.go:186–197](../../../proxy/internal/llm/pricing/pricing.go)) so
|
||||
no formula can yield a negative cost. `Anthropic.TotalTokens` sums all four
|
||||
buckets (in + out + cache_read + cache_creation) — downstream dashboards
|
||||
need to know this differs from `input + output`.
|
||||
`OpenAIParser.ExtractPrompt` falls through `messages → input → prompt`; a
|
||||
@@ -338,22 +374,27 @@ noting).
|
||||
|
||||
**Security.** `Scanner.maxLine = 1 MiB`; a 2 MiB single-line `data:` event
|
||||
errors from `Scanner.Next` and both accumulators stop with partial usage.
|
||||
Pricing file 1 MiB cap is orders of magnitude larger than realistic. Confirm
|
||||
new schema additions are mirrored in both `pricingFile` and `Entry`;
|
||||
`KnownFields(true)` will reject silently-typo'd operator overrides
|
||||
otherwise.
|
||||
Pricing is no longer file-backed, so the loader's path-traversal / symlink /
|
||||
oversize surface is gone entirely — the config channel (an authenticated
|
||||
mapping push from management) is now the only way rates enter the proxy, and
|
||||
`NewEntries` is the validation boundary on it. A new rate added to management's
|
||||
`pricing.Entry` but not to `EntryJSON` here is the remaining silent-mispricing
|
||||
path (see invariant 6).
|
||||
|
||||
**Concurrency.** `Loader.table` is `atomic.Pointer[Table]`; readers never
|
||||
block or see a torn table. `Loader.Reload` is one goroutine, cancelled via
|
||||
context (`TestLoader_ReloadBackgroundLoopCancellation`). `DefaultTable()`
|
||||
uses `sync.Once`. Per-call `Scanner` instances mean no shared state across
|
||||
concurrent response-parser calls.
|
||||
**Concurrency.** Nothing in this package is shared mutable state: tables are
|
||||
built once and never written again, so `cost_meter`'s hot path is lock-free by
|
||||
construction rather than by atomic swap. Per-call `Scanner` instances mean no
|
||||
shared state across concurrent response-parser calls.
|
||||
|
||||
**Perf.** `Table.Cost` is two map lookups + multiplications, O(1).
|
||||
`Scanner.Next` is one `ReadString('\n')` per line. Pricing reload poll 30s.
|
||||
**Perf.** `Table.Cost` is two map lookups + multiplications, O(1); the
|
||||
per-provider-record tier adds at most one more lookup. `Scanner.Next` is one
|
||||
`ReadString('\n')` per line. No background goroutines and no per-request
|
||||
allocation of pricing state.
|
||||
|
||||
**Observability.** Reload failures count via `metric.Int64Counter` keyed
|
||||
`plugin`; warning log rate-limited at 5 min so a broken file doesn't flood.
|
||||
**Observability.** A config carrying no `pricing` block logs one warning at
|
||||
chain-build time (`cost_meter` factory) and then records
|
||||
`cost.skipped=unknown_model` per request, so an old-management deployment is
|
||||
visible in both logs and the access log rather than quietly reporting $0.
|
||||
Parser errors return sentinels — middleware uses `errors.Is` to map to the
|
||||
right `cost.skipped` reason.
|
||||
|
||||
@@ -365,7 +406,7 @@ right `cost.skipped` reason.
|
||||
| `openai_test.go` | 11 | Chat Completions + Responses API + legacy `prompt`; cached-tokens subset for both naming conventions; fixture replays |
|
||||
| `anthropic_test.go` | 7 | Messages + legacy `/v1/complete`; streaming REJECTED on `ParseResponse` (must use scanner); fixture replays |
|
||||
| `sse_test.go` | 12 | Fixture replay both providers; multiline `data:`; CRLF; comment skip; trailing-event-without-blank-line; oversize rejection |
|
||||
| `pricing/pricing_test.go` | 21 | Provider-shape switch; cached-rate fallback; cached-clamp; symlink rejection (target outside basedir + symlink to file); path validation matrix; oversize rejection; reload-keeps-previous-on-parse-error; mtime change detection; goroutine cancellation |
|
||||
| `pricing/pricing_test.go` | 10 | Provider-shape switch (surface selects the formula); cached-rate + cache-read/creation fallback to `InputPer1K`; cached-clamp; negative-token clamp; nil-receiver safety; rate validation (negative / NaN / Inf rejected); nil + empty table |
|
||||
|
||||
**Fixtures** ([proxy/internal/llm/fixtures/](../../../proxy/internal/llm/fixtures/)):
|
||||
`openai_chat_completion.json` (chat.completions with usage),
|
||||
@@ -373,14 +414,15 @@ right `cost.skipped` reason.
|
||||
`openai_stream.txt` (3 deltas + usage + `[DONE]`),
|
||||
`anthropic_messages.json` (Messages API non-streaming),
|
||||
`anthropic_stream.txt` (full 7-event sequence: message_start →
|
||||
content_block_{start,delta×2,stop} → message_delta (usage) → message_stop),
|
||||
`pricing.yaml` (realistic-pricing starter for operator overrides).
|
||||
content_block_{start,delta×2,stop} → message_delta (usage) → message_stop).
|
||||
No pricing fixture: the table is config-delivered, so pricing tests construct
|
||||
it in-process from a wire-shape map.
|
||||
|
||||
## Cross-references
|
||||
|
||||
- Sibling: [31-proxy-middleware-builtin.md](./31-proxy-middleware-builtin.md)
|
||||
— the chain that calls `llm.Parsers()`, `llm.ParserByName`,
|
||||
`llm.NewScanner`, `pricing.NewLoader`.
|
||||
`llm.NewScanner`, `pricing.NewTable` / `pricing.NewEntries`.
|
||||
- Path-routed providers (Vertex AI + Bedrock), credential syntax, and the
|
||||
Bedrock AWS event-stream accumulator:
|
||||
[50-path-routed-providers.md](./50-path-routed-providers.md).
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# proxy/runtime — translate + serve + log
|
||||
|
||||
> **Risk level:** High — every config push from management is translated here, and the chain runs on every HTTP request to a synth target.
|
||||
> **Backward-compat impact:** Additive at the wire (`PathTargetOptions.middlewares`, `agent_network`, `disable_access_log`, capture caps) and on the proxy `Server` struct (`MiddlewareDataDir`, `MiddlewareCaptureBudgetBytes`). Non-agent-network targets stay on the no-middleware fast path.
|
||||
> **Backward-compat impact:** Additive at the wire (`PathTargetOptions.middlewares`, `agent_network`, `disable_access_log`, capture caps) and on the proxy `Server` struct (`MiddlewareCaptureBudgetBytes`). Non-agent-network targets stay on the no-middleware fast path. Middleware config is entirely wire-delivered — no proxy-side data dir is involved, including for LLM pricing, which management ships inside `cost_meter`'s config.
|
||||
|
||||
## Module boundary
|
||||
|
||||
@@ -114,8 +114,7 @@ At **request time** the access-log middleware stamps `CapturedData`; the auth ch
|
||||
|
||||
## Public contracts touched
|
||||
|
||||
- `proxy.Server.MiddlewareDataDir` (string) — base dir for file-backed middleware config (server.go:238-241).
|
||||
- `proxy.Server.MiddlewareCaptureBudgetBytes` (int64) — process-wide capture cap; defaults to 256 MiB (server.go:248-250).
|
||||
- `proxy.Server.MiddlewareCaptureBudgetBytes` (int64) — process-wide capture cap; defaults to 256 MiB (server.go:249-253). There is no `MiddlewareDataDir`: no built-in middleware reads config from disk, so `builtin.FactoryContext` carries only the proxy-lifetime context, meter, logger, and management client.
|
||||
- `proxy/internal/proxy.WithMiddlewareManager(*middleware.Manager) Option` — new option on `NewReverseProxy`; nil keeps the fast path (reverseproxy.go:48-56).
|
||||
- `proxy/internal/proxy.PathTarget` adds `Middlewares`, `CaptureConfig`, `AgentNetwork`, `DisableAccessLog` (servicemapping.go:27-51), all zero-default.
|
||||
- `proxy/internal/proxy.CapturedData` adds `agentNetwork`, `suppressAccessLog`, `userGroupNames` behind `sync.RWMutex`; slices deep-copied (context.go:47-66, 183-258).
|
||||
|
||||
@@ -87,9 +87,9 @@ strips the `@version` suffix from the model, and maps the publisher to a parser
|
||||
surface via `vertexPublisherVendor`:
|
||||
|
||||
- `anthropic` → `llm.provider="anthropic"` → metered through the Anthropic
|
||||
parser, priced under the **`anthropic`** block in `defaults_pricing.yaml`
|
||||
(the parser emits the standard Anthropic provider label, so Vertex Claude
|
||||
reuses first-party Anthropic prices).
|
||||
parser, priced under the **`anthropic`** surface of the pricing table
|
||||
management ships (the parser emits the standard Anthropic provider label, so
|
||||
Vertex Claude reuses first-party Anthropic prices).
|
||||
- `openai` → `llm.provider="openai"` (reserved; not in the catalog lineup
|
||||
today).
|
||||
- anything else (notably `google` / Gemini) → empty vendor → **no parser**.
|
||||
@@ -104,8 +104,9 @@ is omitted from the catalog.
|
||||
|
||||
> Caveat: cross-region inference profiles in `eu` / `apac` carry a ~10% price
|
||||
> premium that the base per-token rates do **not** model — cost annotations for
|
||||
> those regions read low. Operators who need exact regional billing override
|
||||
> the affected entries in `pricing.yaml`.
|
||||
> those regions read low. Operators who need exact regional billing set the
|
||||
> affected models' prices on the provider record, or replace the default entries
|
||||
> via management's `AgentNetwork.PricingDefaultsFile`.
|
||||
|
||||
## AWS Bedrock (`bedrock_api`)
|
||||
|
||||
@@ -211,15 +212,19 @@ so a model-listing call can't be rewritten onto an upstream that would 404 it.
|
||||
## Catalog ↔ pricing cross-check
|
||||
|
||||
Catalog prices and context windows are cross-checked against LiteLLM's
|
||||
`model_prices_and_context_window.json`. The proxy's embedded
|
||||
`defaults_pricing.yaml` covers **every metered first-party model** the catalog
|
||||
enumerates — guarded by
|
||||
`TestDefaultTable_FirstPartyModelCoverage`
|
||||
([pricing/defaults_coverage_test.go](../../../proxy/internal/llm/pricing/defaults_coverage_test.go)),
|
||||
which fails if a catalog model has no embedded price. Bedrock entries are keyed
|
||||
by the **normalised** id the request parser emits (region prefix + version
|
||||
suffix stripped). Vertex Claude carries no Bedrock-style prefix, so it prices
|
||||
straight off the `anthropic` block.
|
||||
`model_prices_and_context_window.json`. The **catalog is the source of default
|
||||
prices**: management's `pricing.DefaultTable` folds every catalog provider's
|
||||
models into the surfaces that provider declares (`PricingSurfaces`), so coverage
|
||||
is structural rather than maintained in a parallel file
|
||||
([pricing/defaults.go](../../../management/internals/modules/agentnetwork/pricing/defaults.go)).
|
||||
`TestDefaultTable_CoversEveryCatalogModel` fails if a catalog model ends up
|
||||
unpriced, and `TestDefaultTable_NoConflictingContributions` fails if two
|
||||
providers contribute the same (surface, model) at different rates. Bedrock
|
||||
entries are keyed by the **normalised** id the request parser emits (region
|
||||
prefix + version suffix stripped) — management applies the same normalisation to
|
||||
per-provider prices at synth time, so the two keys compare equal. Vertex Claude
|
||||
carries no Bedrock-style prefix, so it prices straight off the `anthropic`
|
||||
surface.
|
||||
|
||||
## Things to scrutinise
|
||||
|
||||
@@ -232,16 +237,17 @@ operator-misconfigured Vertex provider and unmetered Gemini traffic; verify
|
||||
publishers).
|
||||
|
||||
**Correctness.** `normalizeBedrockModel` is the join between the wire id and the
|
||||
pricing key — a model that normalises to something not in `defaults_pricing.yaml`
|
||||
meters at `cost.skipped=unknown_model` rather than failing the request. The
|
||||
pricing key — a model that normalises to something absent from the shipped
|
||||
pricing table meters at `cost.skipped=unknown_model` rather than failing the
|
||||
request. The
|
||||
`/bedrock` prefix strip must run on both the parser side (so the model is
|
||||
extracted) and the router side (so the upstream path is native); a regression in
|
||||
either silently breaks the other.
|
||||
|
||||
**Metering caveats.** eu/apac cross-region Bedrock + Vertex profiles carry a
|
||||
~10% premium not modelled by base pricing — flagged in both the catalog comment
|
||||
and `defaults_pricing.yaml`. Operators needing exact regional billing override
|
||||
the relevant entries.
|
||||
~10% premium not modelled by base pricing — flagged in the catalog comment.
|
||||
Operators needing exact regional billing set per-provider prices on the model
|
||||
rows (or replace the default entries via `AgentNetwork.PricingDefaultsFile`).
|
||||
|
||||
## Cross-references
|
||||
|
||||
|
||||
12
funding.json
12
funding.json
@@ -6,7 +6,7 @@
|
||||
"name": "NetBird GmbH",
|
||||
"email": "hello@netbird.io",
|
||||
"phone": "",
|
||||
"description": "NetBird GmbH is a Berlin-based software company specializing in the development of open-source network security solutions. Network security is utterly complex and expensive, accessible only to companies with multi-million dollar IT budgets. In contrast, there are millions of companies left behind. Our mission is to create an advanced network and cybersecurity platform that is both easy-to-use and affordable for teams of all sizes and budgets. By leveraging the open-source strategy and technological advancements, NetBird aims to set the industry standard for connecting and securing IT infrastructure.",
|
||||
"description": "NetBird GmbH is a Berlin-based software company specializing in the development of open source network security solutions. Network security is utterly complex and expensive, accessible only to companies with multi-million dollar IT budgets. In contrast, there are millions of companies left behind. Our mission is to create an advanced network and cybersecurity platform that is both easy-to-use and affordable for teams of all sizes and budgets. By leveraging the open source strategy and technological advancements, NetBird aims to set the industry standard for connecting and securing IT infrastructure.",
|
||||
"webpageUrl": {
|
||||
"url": "https://github.com/netbirdio"
|
||||
}
|
||||
@@ -15,7 +15,7 @@
|
||||
{
|
||||
"guid": "netbird",
|
||||
"name": "NetBird",
|
||||
"description": "NetBird is a configuration-free peer-to-peer private network and a centralized access control system combined in a single open-source platform. It makes it easy to create secure WireGuard-based private networks for your organization or home.",
|
||||
"description": "NetBird is a configuration-free peer-to-peer private network and a centralized access control system combined in a single open source platform. It makes it easy to create secure WireGuard-based private networks for your organization or home.",
|
||||
"webpageUrl": {
|
||||
"url": "https://github.com/netbirdio/netbird"
|
||||
},
|
||||
@@ -59,7 +59,7 @@
|
||||
"guid": "support-yearly",
|
||||
"status": "active",
|
||||
"name": "Support Open Source Development and Maintenance - Yearly",
|
||||
"description": "This will help us partially cover the yearly cost of maintaining the open-source NetBird project.",
|
||||
"description": "This will help us partially cover the yearly cost of maintaining the open source NetBird project.",
|
||||
"amount": 100000,
|
||||
"currency": "USD",
|
||||
"frequency": "yearly",
|
||||
@@ -72,7 +72,7 @@
|
||||
"guid": "support-one-time-year",
|
||||
"status": "active",
|
||||
"name": "Support Open Source Development and Maintenance - One Year",
|
||||
"description": "This will help us partially cover the yearly cost of maintaining the open-source NetBird project.",
|
||||
"description": "This will help us partially cover the yearly cost of maintaining the open source NetBird project.",
|
||||
"amount": 100000,
|
||||
"currency": "USD",
|
||||
"frequency": "one-time",
|
||||
@@ -85,7 +85,7 @@
|
||||
"guid": "support-one-time-monthly",
|
||||
"status": "active",
|
||||
"name": "Support Open Source Development and Maintenance - Monthly",
|
||||
"description": "This will help us partially cover the monthly cost of maintaining the open-source NetBird project.",
|
||||
"description": "This will help us partially cover the monthly cost of maintaining the open source NetBird project.",
|
||||
"amount": 10000,
|
||||
"currency": "USD",
|
||||
"frequency": "monthly",
|
||||
@@ -98,7 +98,7 @@
|
||||
"guid": "support-monthly",
|
||||
"status": "active",
|
||||
"name": "Support Open Source Development and Maintenance - One Month",
|
||||
"description": "This will help us partially cover the monthly cost of maintaining the open-source NetBird project.",
|
||||
"description": "This will help us partially cover the monthly cost of maintaining the open source NetBird project.",
|
||||
"amount": 10000,
|
||||
"currency": "USD",
|
||||
"frequency": "monthly",
|
||||
|
||||
@@ -4607,7 +4607,7 @@ components:
|
||||
|
||||
FleetDMMatchAttributes:
|
||||
type: object
|
||||
description: Attribute conditions to match when approving FleetDM hosts. Most attributes work with FleetDM's free/open-source version. Premium-only attributes are marked accordingly
|
||||
description: Attribute conditions to match when approving FleetDM hosts. Most attributes work with FleetDM's free/open source version. Premium-only attributes are marked accordingly
|
||||
additionalProperties: false
|
||||
properties:
|
||||
disk_encryption_enabled:
|
||||
|
||||
@@ -2852,7 +2852,7 @@ type EDRFleetDMRequest struct {
|
||||
// LastSyncedInterval The devices last sync requirement interval in hours. Minimum value is 24 hours
|
||||
LastSyncedInterval int `json:"last_synced_interval"`
|
||||
|
||||
// MatchAttributes Attribute conditions to match when approving FleetDM hosts. Most attributes work with FleetDM's free/open-source version. Premium-only attributes are marked accordingly
|
||||
// MatchAttributes Attribute conditions to match when approving FleetDM hosts. Most attributes work with FleetDM's free/open source version. Premium-only attributes are marked accordingly
|
||||
MatchAttributes FleetDMMatchAttributes `json:"match_attributes"`
|
||||
}
|
||||
|
||||
@@ -2885,7 +2885,7 @@ type EDRFleetDMResponse struct {
|
||||
// LastSyncedInterval The devices last sync requirement interval in hours.
|
||||
LastSyncedInterval int `json:"last_synced_interval"`
|
||||
|
||||
// MatchAttributes Attribute conditions to match when approving FleetDM hosts. Most attributes work with FleetDM's free/open-source version. Premium-only attributes are marked accordingly
|
||||
// MatchAttributes Attribute conditions to match when approving FleetDM hosts. Most attributes work with FleetDM's free/open source version. Premium-only attributes are marked accordingly
|
||||
MatchAttributes FleetDMMatchAttributes `json:"match_attributes"`
|
||||
|
||||
// UpdatedAt Timestamp of when the integration was last updated.
|
||||
@@ -3105,7 +3105,7 @@ type Event struct {
|
||||
// EventActivityCode The string code of the activity that occurred during the event
|
||||
type EventActivityCode string
|
||||
|
||||
// FleetDMMatchAttributes Attribute conditions to match when approving FleetDM hosts. Most attributes work with FleetDM's free/open-source version. Premium-only attributes are marked accordingly
|
||||
// FleetDMMatchAttributes Attribute conditions to match when approving FleetDM hosts. Most attributes work with FleetDM's free/open source version. Premium-only attributes are marked accordingly
|
||||
type FleetDMMatchAttributes struct {
|
||||
// DiskEncryptionEnabled Whether disk encryption (FileVault/BitLocker) must be enabled on the host
|
||||
DiskEncryptionEnabled *bool `json:"disk_encryption_enabled,omitempty"`
|
||||
|
||||
Reference in New Issue
Block a user