mirror of
https://github.com/kerberos-io/agent.git
synced 2026-11-23 23:10:50 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b134731fa | ||
|
|
33cc8a46ed | ||
|
|
7d70361870 | ||
|
|
9a9b5d051b | ||
|
|
1492eb6d6c |
@@ -18,6 +18,11 @@ func JWTMiddleWare(configDirectory string) jwt.GinJWTMiddleware {
|
||||
// Kerberos Factory) be validated by the agent. Without it, a random secret
|
||||
// is generated once and stored with the configuration; see loadJWTSecret.
|
||||
myKey := loadJWTSecret(configDirectory)
|
||||
// With an explicitly shared secret, Kerberos Factory signs its own tokens
|
||||
// for the agent under the "factory" service identity. Only holders of that
|
||||
// secret can produce them. With the generated per-install secret, only the
|
||||
// agent's own login issues tokens, so that identity is not accepted.
|
||||
sharedSecret := os.Getenv("AGENT_JWT_SECRET") != ""
|
||||
|
||||
m := jwt.GinJWTMiddleware{
|
||||
Realm: "kerberosio",
|
||||
@@ -94,7 +99,10 @@ func JWTMiddleWare(configDirectory string) jwt.GinJWTMiddleware {
|
||||
// Only the configured account may use the API, even with a
|
||||
// validly signed token.
|
||||
user, ok := data.(*models.User)
|
||||
return ok && user.Username != "" && user.Username == agentUsername()
|
||||
if !ok || user.Username == "" {
|
||||
return false
|
||||
}
|
||||
return user.Username == agentUsername() || (sharedSecret && user.Username == factoryServiceUsername)
|
||||
},
|
||||
Unauthorized: func(c *gin.Context, code int, message string) {
|
||||
c.AbortWithStatusJSON(code, gin.H{
|
||||
|
||||
@@ -21,6 +21,9 @@ const (
|
||||
// legacyJWTSecret was the hard-coded fallback in earlier releases. It is
|
||||
// public, so it is never used implicitly.
|
||||
legacyJWTSecret = "TOBECHANGED"
|
||||
// factoryServiceUsername is the identity Kerberos Factory puts in the
|
||||
// tokens it signs with the shared AGENT_JWT_SECRET.
|
||||
factoryServiceUsername = "factory"
|
||||
)
|
||||
|
||||
// loadJWTSecret returns the key used to sign and verify API tokens.
|
||||
|
||||
@@ -70,9 +70,16 @@ func TestLoadJWTSecretReplacesShortStoredSecret(t *testing.T) {
|
||||
|
||||
// securityRouter wires the real middleware and routes the way StartServer does.
|
||||
func securityRouter(t *testing.T) (*gin.Engine, []byte) {
|
||||
t.Helper()
|
||||
return securityRouterWithSecret(t, "")
|
||||
}
|
||||
|
||||
// securityRouterWithSecret is securityRouter with AGENT_JWT_SECRET set to
|
||||
// secret ("" means the generated per-install secret).
|
||||
func securityRouterWithSecret(t *testing.T, secret string) (*gin.Engine, []byte) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
t.Setenv("AGENT_JWT_SECRET", "")
|
||||
t.Setenv("AGENT_JWT_SECRET", secret)
|
||||
t.Setenv("AGENT_USERNAME", "")
|
||||
t.Setenv("AGENT_PASSWORD", "")
|
||||
|
||||
@@ -202,3 +209,29 @@ func TestProfilerRequiresTokenWhenEnabled(t *testing.T) {
|
||||
t.Fatalf("enabled pprof with token: status %d, want 200", code)
|
||||
}
|
||||
}
|
||||
|
||||
// Kerberos Factory signs tokens for the agent with the shared AGENT_JWT_SECRET
|
||||
// under the "factory" identity (uug-ai/factory api/k8sproxy/jwt.go).
|
||||
func TestFactoryTokenAcceptedWithSharedSecret(t *testing.T) {
|
||||
router, key := securityRouterWithSecret(t, "shared-with-factory")
|
||||
if string(key) != "shared-with-factory" {
|
||||
t.Fatalf("middleware key = %q, want the shared secret", key)
|
||||
}
|
||||
token := signedToken(t, key, "factory")
|
||||
|
||||
// An authorised request reaches the handler, which reports the missing file.
|
||||
if code := request(router, "GET", "/file/missing.mp4", token); code != stdhttp.StatusNotFound {
|
||||
t.Fatalf("factory token with shared secret: status %d, want 404 from the handler", code)
|
||||
}
|
||||
if code := request(router, "GET", "/file/missing.mp4", signedToken(t, key, "someone-else")); code != stdhttp.StatusForbidden {
|
||||
t.Fatalf("other identity with shared secret: status %d, want 403", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFactoryIdentityRejectedWithoutSharedSecret(t *testing.T) {
|
||||
router, key := securityRouter(t)
|
||||
|
||||
if code := request(router, "GET", "/file/missing.mp4", signedToken(t, key, "factory")); code != stdhttp.StatusForbidden {
|
||||
t.Fatalf("factory identity with the per-install secret: status %d, want 403", code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -58,21 +59,76 @@ func init() {
|
||||
mqtt.ERROR = pahoErrorLogger{}
|
||||
}
|
||||
|
||||
func enableMQTTConnectionDiagnostics(options *mqtt.ClientOptions, brokerURL string) {
|
||||
if !strings.Contains(brokerURL, "://") {
|
||||
options.SetCustomOpenConnectionFn(openMQTTConnection)
|
||||
return
|
||||
// parseMQTTBrokers turns the configured MQTT URI into the list of brokers to
|
||||
// connect to. Besides a single broker URI it accepts an ActiveMQ-style
|
||||
// failover URI, as used by Amazon MQ active/standby brokers:
|
||||
//
|
||||
// failover:(mqtt+ssl://b-1.example:8883,mqtt+ssl://b-2.example:8883)
|
||||
//
|
||||
// and a plain comma-separated list of broker URIs. Transport options after
|
||||
// the closing parenthesis (e.g. "?randomize=false") are ignored: paho tries
|
||||
// the brokers in the order they are listed, on connect and on reconnect.
|
||||
//
|
||||
// A comma only separates brokers when the text after it starts with a URI
|
||||
// scheme ("scheme://"). Any other comma belongs to the current broker URI,
|
||||
// so existing single-broker URIs with commas in their credentials, path or
|
||||
// query string (e.g. "wss://broker/mqtt?token=a,b") keep working.
|
||||
func parseMQTTBrokers(raw string) []string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if len(raw) >= len("failover:") && strings.EqualFold(raw[:len("failover:")], "failover:") {
|
||||
raw = strings.TrimSpace(raw[len("failover:"):])
|
||||
if strings.HasPrefix(raw, "(") {
|
||||
if end := strings.LastIndex(raw, ")"); end > 0 {
|
||||
raw = raw[1:end]
|
||||
} else {
|
||||
raw = raw[1:]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
parsedURL, err := url.Parse(brokerURL)
|
||||
if err != nil {
|
||||
return
|
||||
segments := []string{}
|
||||
for _, segment := range strings.Split(raw, ",") {
|
||||
if len(segments) > 0 && !mqttBrokerSchemePattern.MatchString(strings.TrimSpace(segment)) {
|
||||
segments[len(segments)-1] += "," + segment
|
||||
continue
|
||||
}
|
||||
segments = append(segments, segment)
|
||||
}
|
||||
|
||||
switch strings.ToLower(parsedURL.Scheme) {
|
||||
case "", "mqtt", "tcp", "ssl", "tls", "mqtts", "mqtt+ssl", "tcps":
|
||||
options.SetCustomOpenConnectionFn(openMQTTConnection)
|
||||
brokers := []string{}
|
||||
for _, broker := range segments {
|
||||
if broker = strings.TrimSpace(broker); broker != "" {
|
||||
brokers = append(brokers, broker)
|
||||
}
|
||||
}
|
||||
return brokers
|
||||
}
|
||||
|
||||
// mqttBrokerSchemePattern matches the start of a URI with a scheme (RFC 3986).
|
||||
var mqttBrokerSchemePattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9+.-]*://`)
|
||||
|
||||
// enableMQTTConnectionDiagnostics installs our instrumented TCP/TLS dialer.
|
||||
// The custom dialer is used for every broker, so it is only installed when
|
||||
// all brokers use a TCP-based scheme (WebSocket brokers keep paho's dialer).
|
||||
func enableMQTTConnectionDiagnostics(options *mqtt.ClientOptions, brokerURLs []string) {
|
||||
if len(brokerURLs) == 0 {
|
||||
return
|
||||
}
|
||||
for _, brokerURL := range brokerURLs {
|
||||
if !strings.Contains(brokerURL, "://") {
|
||||
continue
|
||||
}
|
||||
parsedURL, err := url.Parse(brokerURL)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
switch strings.ToLower(parsedURL.Scheme) {
|
||||
case "", "mqtt", "tcp", "ssl", "tls", "mqtts", "mqtt+ssl", "tcps":
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
options.SetCustomOpenConnectionFn(openMQTTConnection)
|
||||
}
|
||||
|
||||
func openMQTTConnection(uri *url.URL, options mqtt.ClientOptions) (net.Conn, error) {
|
||||
@@ -270,8 +326,11 @@ func ConfigureMQTT(configDirectory string, configuration *models.Configuration,
|
||||
|
||||
// We will set the MQTT endpoint to which we want to connect
|
||||
// and share and receive messages to/from.
|
||||
mqttURL := config.MQTTURI
|
||||
opts.AddBroker(mqttURL)
|
||||
// The URI may list several brokers (failover), paho tries them in order.
|
||||
mqttBrokers := parseMQTTBrokers(config.MQTTURI)
|
||||
for _, broker := range mqttBrokers {
|
||||
opts.AddBroker(broker)
|
||||
}
|
||||
|
||||
// Our MQTT broker can have username/password credentials
|
||||
// to protect it from the outside.
|
||||
@@ -282,7 +341,8 @@ func ConfigureMQTT(configDirectory string, configuration *models.Configuration,
|
||||
opts.SetPassword(mqtt_password)
|
||||
}
|
||||
log.WithFields(log.Fields{
|
||||
"broker_configured": mqttURL != "",
|
||||
"broker_configured": len(mqttBrokers) > 0,
|
||||
"broker_count": len(mqttBrokers),
|
||||
"component": "routers/mqtt",
|
||||
"event": "credentials_configured",
|
||||
"password_configured": mqtt_password != "",
|
||||
@@ -292,7 +352,7 @@ func ConfigureMQTT(configDirectory string, configuration *models.Configuration,
|
||||
// Some extra options to make sure the connection behaves
|
||||
// properly. More information here: github.com/eclipse/paho.mqtt.golang.
|
||||
//opts.SetCleanSession(true)
|
||||
enableMQTTConnectionDiagnostics(opts, mqttURL)
|
||||
enableMQTTConnectionDiagnostics(opts, mqttBrokers)
|
||||
opts.SetCleanSession(false)
|
||||
opts.SetResumeSubs(true)
|
||||
opts.SetStore(mqtt.NewMemoryStore())
|
||||
@@ -354,7 +414,7 @@ func ConfigureMQTT(configDirectory string, configuration *models.Configuration,
|
||||
"event": "connected",
|
||||
}).Info("MQTT broker connected")
|
||||
log.WithFields(log.Fields{
|
||||
"broker_configured": mqttURL != "",
|
||||
"broker_configured": len(mqttBrokers) > 0,
|
||||
"component": "routers/mqtt",
|
||||
"event": "connection_details",
|
||||
}).Debug("MQTT connection details")
|
||||
|
||||
@@ -23,12 +23,15 @@ func TestEnableMQTTConnectionDiagnostics(t *testing.T) {
|
||||
{name: "TCP", brokerURL: "tcp://broker.example:1883", want: true},
|
||||
{name: "default TCP", brokerURL: "broker.example:1883", want: true},
|
||||
{name: "WebSocket", brokerURL: "wss://broker.example/mqtt", want: false},
|
||||
{name: "ActiveMQ failover", brokerURL: "failover:(mqtt+ssl://b-1.example:8883,mqtt+ssl://b-2.example:8883)", want: true},
|
||||
{name: "mixed TCP and WebSocket", brokerURL: "tcp://b-1.example:1883,wss://b-2.example/mqtt", want: false},
|
||||
{name: "empty", brokerURL: "", want: false},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
options := mqtt.NewClientOptions()
|
||||
enableMQTTConnectionDiagnostics(options, test.brokerURL)
|
||||
enableMQTTConnectionDiagnostics(options, parseMQTTBrokers(test.brokerURL))
|
||||
if got := options.CustomOpenConnectionFn != nil; got != test.want {
|
||||
t.Fatalf("CustomOpenConnectionFn configured = %t, want %t", got, test.want)
|
||||
}
|
||||
@@ -206,3 +209,64 @@ func TestRemoteSessionReservationIsIdempotent(t *testing.T) {
|
||||
t.Fatalf("duplicate reserve() error = %v, want %v", err, errRemoteSessionExists)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMQTTBrokers(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
raw string
|
||||
want []string
|
||||
}{
|
||||
{name: "single", raw: "mqtt+ssl://broker.example:8883", want: []string{"mqtt+ssl://broker.example:8883"}},
|
||||
{name: "empty", raw: " ", want: []string{}},
|
||||
{
|
||||
name: "Amazon MQ failover",
|
||||
raw: "failover:(mqtt+ssl://b-1.mq.eu-west-2.amazonaws.com:8883,mqtt+ssl://b-2.mq.eu-west-2.amazonaws.com:8883)",
|
||||
want: []string{"mqtt+ssl://b-1.mq.eu-west-2.amazonaws.com:8883", "mqtt+ssl://b-2.mq.eu-west-2.amazonaws.com:8883"},
|
||||
},
|
||||
{
|
||||
name: "failover with spaces and transport options",
|
||||
raw: " FAILOVER:( ssl://b-1.example:8883 , ssl://b-2.example:8883 )?randomize=false",
|
||||
want: []string{"ssl://b-1.example:8883", "ssl://b-2.example:8883"},
|
||||
},
|
||||
{name: "failover without parentheses", raw: "failover:tcp://b-1.example:1883", want: []string{"tcp://b-1.example:1883"}},
|
||||
{name: "comma separated", raw: "tcp://b-1.example:1883,tcp://b-2.example:1883", want: []string{"tcp://b-1.example:1883", "tcp://b-2.example:1883"}},
|
||||
{name: "comma in query string", raw: "wss://broker.example/mqtt?token=a,b", want: []string{"wss://broker.example/mqtt?token=a,b"}},
|
||||
{name: "comma in password", raw: "mqtt+ssl://user:p,ss@broker.example:8883", want: []string{"mqtt+ssl://user:p,ss@broker.example:8883"}},
|
||||
{name: "comma in path", raw: "wss://broker.example/a,b/mqtt", want: []string{"wss://broker.example/a,b/mqtt"}},
|
||||
{name: "comma followed by text that looks like a scheme without slashes", raw: "wss://broker.example/mqtt?list=a,b:c", want: []string{"wss://broker.example/mqtt?list=a,b:c"}},
|
||||
{
|
||||
name: "failover with commas inside a broker URI",
|
||||
raw: "failover:(wss://b-1.example/mqtt?token=a,b,wss://b-2.example/mqtt?token=c,d)",
|
||||
want: []string{"wss://b-1.example/mqtt?token=a,b", "wss://b-2.example/mqtt?token=c,d"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got := parseMQTTBrokers(test.raw)
|
||||
if len(got) != len(test.want) {
|
||||
t.Fatalf("parseMQTTBrokers(%q) = %q, want %q", test.raw, got, test.want)
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != test.want[i] {
|
||||
t.Fatalf("parseMQTTBrokers(%q) = %q, want %q", test.raw, got, test.want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureMQTTOptionsRegistersFailoverBrokers(t *testing.T) {
|
||||
options := mqtt.NewClientOptions()
|
||||
for _, broker := range parseMQTTBrokers("failover:(mqtt+ssl://b-1.example:8883,mqtt+ssl://b-2.example:8883)") {
|
||||
options.AddBroker(broker)
|
||||
}
|
||||
if len(options.Servers) != 2 {
|
||||
t.Fatalf("registered %d brokers, want 2", len(options.Servers))
|
||||
}
|
||||
for i, host := range []string{"b-1.example:8883", "b-2.example:8883"} {
|
||||
if options.Servers[i].Scheme != "mqtt+ssl" || options.Servers[i].Host != host {
|
||||
t.Fatalf("broker %d = %s, want mqtt+ssl://%s", i, options.Servers[i], host)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user