diff --git a/.github/workflows/release-bump.yml b/.github/workflows/release-bump.yml index be78831..cbc1e98 100644 --- a/.github/workflows/release-bump.yml +++ b/.github/workflows/release-bump.yml @@ -22,10 +22,12 @@ env: jobs: # Determine the next version, create the GitHub release and expose the tag. bump-release: - uses: uug-ai/workflows/.github/workflows/release-bump.yml@main + # Pinned to a reviewed commit of uug-ai/workflows so changes there cannot + # alter this release without a change here. It only needs GITHUB_TOKEN, + # which GitHub provides to called workflows, so no secrets are passed on. + uses: uug-ai/workflows/.github/workflows/release-bump.yml@6c1805abf25ac34add01d4af711277e8a68945ab # main as of 2026-11-20 with: bump: ${{ github.event.inputs.bump }} - secrets: inherit # Publish the platform image to the uug-ai GitHub Container Registry # (ghcr.io/uug-ai/agent-platform). @@ -56,6 +58,9 @@ jobs: strategy: matrix: architecture: [amd64] + env: + ARCH: ${{ matrix.architecture }} + RELEASE_TAG: ${{ needs.bump-release.outputs.tag }} steps: - name: Login to DockerHub uses: docker/login-action@v3 @@ -66,16 +71,16 @@ jobs: uses: actions/checkout@v4 - name: Run Build run: | - docker build --provenance=false --build-arg VERSION=${{ needs.bump-release.outputs.tag }} -t ${{matrix.architecture}} . - CID=$(docker create ${{matrix.architecture}}) - docker cp ${CID}:/home/agent ./output-${{matrix.architecture}} - docker rm ${CID} + docker build --provenance=false --build-arg VERSION="${RELEASE_TAG}" -t "${ARCH}" . + CID=$(docker create "${ARCH}") + docker cp "${CID}:/home/agent" "./output-${ARCH}" + docker rm "${CID}" - name: Strip binary - run: tar -cf agent-${{matrix.architecture}}.tar -C output-${{matrix.architecture}} . && rm -rf output-${{matrix.architecture}} + run: tar -cf "agent-${ARCH}.tar" -C "output-${ARCH}" . && rm -rf "output-${ARCH}" - name: Build and push Docker image run: | - docker tag ${{matrix.architecture}} $REPO-arch:arch-${{matrix.architecture}}-${{ needs.bump-release.outputs.tag }} - docker push $REPO-arch:arch-${{matrix.architecture}}-${{ needs.bump-release.outputs.tag }} + docker tag "${ARCH}" "${REPO}-arch:arch-${ARCH}-${RELEASE_TAG}" + docker push "${REPO}-arch:arch-${ARCH}-${RELEASE_TAG}" - name: Upload artifact uses: actions/upload-artifact@v4 with: @@ -90,6 +95,9 @@ jobs: strategy: matrix: architecture: [arm64] + env: + ARCH: ${{ matrix.architecture }} + RELEASE_TAG: ${{ needs.bump-release.outputs.tag }} steps: - name: Login to DockerHub uses: docker/login-action@v3 @@ -100,16 +108,16 @@ jobs: uses: actions/checkout@v4 - name: Run Build run: | - docker build --provenance=false --build-arg VERSION=${{ needs.bump-release.outputs.tag }} -t ${{matrix.architecture}} . - CID=$(docker create ${{matrix.architecture}}) - docker cp ${CID}:/home/agent ./output-${{matrix.architecture}} - docker rm ${CID} + docker build --provenance=false --build-arg VERSION="${RELEASE_TAG}" -t "${ARCH}" . + CID=$(docker create "${ARCH}") + docker cp "${CID}:/home/agent" "./output-${ARCH}" + docker rm "${CID}" - name: Strip binary - run: tar -cf agent-${{matrix.architecture}}.tar -C output-${{matrix.architecture}} . && rm -rf output-${{matrix.architecture}} + run: tar -cf "agent-${ARCH}.tar" -C "output-${ARCH}" . && rm -rf "output-${ARCH}" - name: Build and push Docker image run: | - docker tag ${{matrix.architecture}} $REPO-arch:arch-${{matrix.architecture}}-${{ needs.bump-release.outputs.tag }} - docker push $REPO-arch:arch-${{matrix.architecture}}-${{ needs.bump-release.outputs.tag }} + docker tag "${ARCH}" "${REPO}-arch:arch-${ARCH}-${RELEASE_TAG}" + docker push "${REPO}-arch:arch-${ARCH}-${RELEASE_TAG}" - name: Upload artifact uses: actions/upload-artifact@v4 with: @@ -119,6 +127,8 @@ jobs: create-manifest: runs-on: ubuntu-24.04 needs: [bump-release, build-amd64, build-arm64] + env: + RELEASE_TAG: ${{ needs.bump-release.outputs.tag }} steps: - name: Login to DockerHub uses: docker/login-action@v3 @@ -127,16 +137,16 @@ jobs: password: ${{ secrets.DOCKER_PASSWORD }} - name: Create and push multi-arch manifest run: | - docker manifest create $REPO:${{ needs.bump-release.outputs.tag }} \ - $REPO-arch:arch-amd64-${{ needs.bump-release.outputs.tag }} \ - $REPO-arch:arch-arm64-${{ needs.bump-release.outputs.tag }} - docker manifest push $REPO:${{ needs.bump-release.outputs.tag }} + docker manifest create "${REPO}:${RELEASE_TAG}" \ + "${REPO}-arch:arch-amd64-${RELEASE_TAG}" \ + "${REPO}-arch:arch-arm64-${RELEASE_TAG}" + docker manifest push "${REPO}:${RELEASE_TAG}" - name: Create and push latest manifest run: | - docker manifest create $REPO:latest \ - $REPO-arch:arch-amd64-${{ needs.bump-release.outputs.tag }} \ - $REPO-arch:arch-arm64-${{ needs.bump-release.outputs.tag }} - docker manifest push $REPO:latest + docker manifest create "${REPO}:latest" \ + "${REPO}-arch:arch-amd64-${RELEASE_TAG}" \ + "${REPO}-arch:arch-arm64-${RELEASE_TAG}" + docker manifest push "${REPO}:latest" create-release: runs-on: ubuntu-24.04 diff --git a/.github/workflows/release-create.yml b/.github/workflows/release-create.yml index a63bf07..30344dc 100644 --- a/.github/workflows/release-create.yml +++ b/.github/workflows/release-create.yml @@ -11,6 +11,9 @@ on: env: REPO: kerberos/agent + # Expressions are passed to shell steps through the environment and quoted, + # never interpolated into the script, so a crafted tag cannot inject commands. + RELEASE_TAG: ${{ github.event.inputs.tag || github.ref_name }} jobs: build-amd64: @@ -20,7 +23,15 @@ jobs: strategy: matrix: architecture: [amd64] + env: + ARCH: ${{ matrix.architecture }} steps: + - name: Validate release tag + run: | + if [[ ! "${RELEASE_TAG}" =~ ^[A-Za-z0-9._-]+$ ]]; then + echo "Invalid release tag: only letters, digits, '.', '_' and '-' are allowed." >&2 + exit 1 + fi - name: Login to DockerHub uses: docker/login-action@v3 with: @@ -30,16 +41,16 @@ jobs: uses: actions/checkout@v4 - name: Run Build run: | - docker build --provenance=false --build-arg VERSION=${{github.event.inputs.tag || github.ref_name}} -t ${{matrix.architecture}} . - CID=$(docker create ${{matrix.architecture}}) - docker cp ${CID}:/home/agent ./output-${{matrix.architecture}} - docker rm ${CID} + docker build --provenance=false --build-arg VERSION="${RELEASE_TAG}" -t "${ARCH}" . + CID=$(docker create "${ARCH}") + docker cp "${CID}:/home/agent" "./output-${ARCH}" + docker rm "${CID}" - name: Strip binary - run: tar -cf agent-${{matrix.architecture}}.tar -C output-${{matrix.architecture}} . && rm -rf output-${{matrix.architecture}} + run: tar -cf "agent-${ARCH}.tar" -C "output-${ARCH}" . && rm -rf "output-${ARCH}" - name: Build and push Docker image run: | - docker tag ${{matrix.architecture}} $REPO-arch:arch-${{matrix.architecture}}-${{github.event.inputs.tag || github.ref_name}} - docker push $REPO-arch:arch-${{matrix.architecture}}-${{github.event.inputs.tag || github.ref_name}} + docker tag "${ARCH}" "${REPO}-arch:arch-${ARCH}-${RELEASE_TAG}" + docker push "${REPO}-arch:arch-${ARCH}-${RELEASE_TAG}" - name: Upload artifact uses: actions/upload-artifact@v4 with: @@ -53,7 +64,15 @@ jobs: strategy: matrix: architecture: [arm64] + env: + ARCH: ${{ matrix.architecture }} steps: + - name: Validate release tag + run: | + if [[ ! "${RELEASE_TAG}" =~ ^[A-Za-z0-9._-]+$ ]]; then + echo "Invalid release tag: only letters, digits, '.', '_' and '-' are allowed." >&2 + exit 1 + fi - name: Login to DockerHub uses: docker/login-action@v3 with: @@ -63,16 +82,16 @@ jobs: uses: actions/checkout@v4 - name: Run Build run: | - docker build --provenance=false --build-arg VERSION=${{github.event.inputs.tag || github.ref_name}} -t ${{matrix.architecture}} . - CID=$(docker create ${{matrix.architecture}}) - docker cp ${CID}:/home/agent ./output-${{matrix.architecture}} - docker rm ${CID} + docker build --provenance=false --build-arg VERSION="${RELEASE_TAG}" -t "${ARCH}" . + CID=$(docker create "${ARCH}") + docker cp "${CID}:/home/agent" "./output-${ARCH}" + docker rm "${CID}" - name: Strip binary - run: tar -cf agent-${{matrix.architecture}}.tar -C output-${{matrix.architecture}} . && rm -rf output-${{matrix.architecture}} + run: tar -cf "agent-${ARCH}.tar" -C "output-${ARCH}" . && rm -rf "output-${ARCH}" - name: Build and push Docker image run: | - docker tag ${{matrix.architecture}} $REPO-arch:arch-${{matrix.architecture}}-${{github.event.inputs.tag || github.ref_name}} - docker push $REPO-arch:arch-${{matrix.architecture}}-${{github.event.inputs.tag || github.ref_name}} + docker tag "${ARCH}" "${REPO}-arch:arch-${ARCH}-${RELEASE_TAG}" + docker push "${REPO}-arch:arch-${ARCH}-${RELEASE_TAG}" - name: Upload artifact uses: actions/upload-artifact@v4 with: @@ -90,16 +109,16 @@ jobs: password: ${{ secrets.DOCKER_PASSWORD }} - name: Create and push multi-arch manifest run: | - docker manifest create $REPO:${{ github.event.inputs.tag || github.ref_name }} \ - $REPO-arch:arch-amd64-${{github.event.inputs.tag || github.ref_name}} \ - $REPO-arch:arch-arm64-${{github.event.inputs.tag || github.ref_name}} - docker manifest push $REPO:${{ github.event.inputs.tag || github.ref_name }} + docker manifest create "${REPO}:${RELEASE_TAG}" \ + "${REPO}-arch:arch-amd64-${RELEASE_TAG}" \ + "${REPO}-arch:arch-arm64-${RELEASE_TAG}" + docker manifest push "${REPO}:${RELEASE_TAG}" - name: Create and push latest manifest run: | - docker manifest create $REPO:latest \ - $REPO-arch:arch-amd64-${{github.event.inputs.tag || github.ref_name}} \ - $REPO-arch:arch-arm64-${{github.event.inputs.tag || github.ref_name}} - docker manifest push $REPO:latest + docker manifest create "${REPO}:latest" \ + "${REPO}-arch:arch-amd64-${RELEASE_TAG}" \ + "${REPO}-arch:arch-arm64-${RELEASE_TAG}" + docker manifest push "${REPO}:latest" if: github.event.inputs.tag == 'test' create-release: diff --git a/machinery/src/routers/http/health_test.go b/machinery/src/routers/http/health_test.go index 4918eff..0343b6d 100644 --- a/machinery/src/routers/http/health_test.go +++ b/machinery/src/routers/http/health_test.go @@ -16,7 +16,7 @@ import ( func TestHealthCheckReturnsStandardPublicResponse(t *testing.T) { gin.SetMode(gin.TestMode) - middlewareConfig := JWTMiddleWare() + middlewareConfig := JWTMiddleWare(t.TempDir()) authMiddleware, err := jwt.New(&middlewareConfig) if err != nil { t.Fatalf("initialize JWT middleware: %v", err) diff --git a/machinery/src/routers/http/jwt_middleware.go b/machinery/src/routers/http/jwt_middleware.go index 4fbe572..d4bbaf7 100644 --- a/machinery/src/routers/http/jwt_middleware.go +++ b/machinery/src/routers/http/jwt_middleware.go @@ -11,21 +11,17 @@ import ( "github.com/kerberos-io/agent/machinery/src/models" ) -func JWTMiddleWare() jwt.GinJWTMiddleware { +func JWTMiddleWare(configDirectory string) jwt.GinJWTMiddleware { identityKey := "id" - // Allow the JWT signing secret to be configured through an environment - // variable so that tokens issued by another service (e.g. the Kerberos - // Factory) can be validated by the agent. Falls back to the historic - // default to preserve backwards compatibility. - myKey := os.Getenv("AGENT_JWT_SECRET") - if myKey == "" { - myKey = "TOBECHANGED" - } + // AGENT_JWT_SECRET lets tokens issued by another service (e.g. the + // 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) m := jwt.GinJWTMiddleware{ Realm: "kerberosio", - Key: []byte(myKey), + Key: myKey, Timeout: time.Hour * 24, MaxRefresh: time.Hour * 24 * 7, IdentityKey: identityKey, @@ -39,10 +35,15 @@ func JWTMiddleWare() jwt.GinJWTMiddleware { }, IdentityHandler: func(c *gin.Context) interface{} { claims := jwt.ExtractClaims(c) - user := claims["id"].(map[string]interface{}) + user, ok := claims["id"].(map[string]interface{}) + if !ok { + return nil + } + username, _ := user["username"].(string) + role, _ := user["role"].(string) return &models.User{ - Username: user["username"].(string), - Role: user["role"].(string), + Username: username, + Role: role, } }, Authenticator: func(c *gin.Context) (interface{}, error) { @@ -53,11 +54,7 @@ func JWTMiddleWare() jwt.GinJWTMiddleware { username := loginVals.Username password := loginVals.Password - // Get username from ENV - usernameFromConfig := os.Getenv("AGENT_USERNAME") - if usernameFromConfig == "" { - usernameFromConfig = "root" - } + usernameFromConfig := agentUsername() // Get password from ENV passwordFromConfig := os.Getenv("AGENT_PASSWORD") if passwordFromConfig == "" { @@ -76,7 +73,7 @@ func JWTMiddleWare() jwt.GinJWTMiddleware { LoginResponse: func(c *gin.Context, code int, token string, expire time.Time) { // Decrypt the token - hmacSecret := []byte(myKey) // todo in config file + hmacSecret := myKey t, _ := jwtgo.Parse(token, func(token *jwtgo.Token) (interface{}, error) { return hmacSecret, nil }) @@ -94,10 +91,10 @@ func JWTMiddleWare() jwt.GinJWTMiddleware { }) }, Authorizator: func(data interface{}, c *gin.Context) bool { - if _, ok := data.(*models.User); ok { //&& v.Username == "admin" { - return true - } - return false + // 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() }, Unauthorized: func(c *gin.Context, code int, message string) { c.AbortWithStatusJSON(code, gin.H{ diff --git a/machinery/src/routers/http/jwt_secret.go b/machinery/src/routers/http/jwt_secret.go new file mode 100644 index 0000000..e5502d5 --- /dev/null +++ b/machinery/src/routers/http/jwt_secret.go @@ -0,0 +1,113 @@ +package http + +import ( + "crypto/rand" + "encoding/hex" + "errors" + "os" + "path/filepath" + "strings" + + log "github.com/sirupsen/logrus" +) + +const ( + // jwtSecretFileName lives next to config.json so it persists on the same + // volume and survives restarts and upgrades. + jwtSecretFileName = "jwt_secret" + // minJWTSecretLength is the shortest persisted secret that is accepted. + // Generated secrets are 64 hex characters (32 random bytes). + minJWTSecretLength = 32 + // legacyJWTSecret was the hard-coded fallback in earlier releases. It is + // public, so it is never used implicitly. + legacyJWTSecret = "TOBECHANGED" +) + +// loadJWTSecret returns the key used to sign and verify API tokens. +// +// AGENT_JWT_SECRET always wins, so deployments that share a secret with +// another service (such as Kerberos Factory) keep working. Without it, a +// random secret is generated on first start and stored in +// /data/config/jwt_secret. If that file cannot be written, +// an in-memory random secret is used, which means users must sign in again +// after a restart. +func loadJWTSecret(configDirectory string) []byte { + if secret := os.Getenv("AGENT_JWT_SECRET"); secret != "" { + if secret == legacyJWTSecret { + log.WithFields(log.Fields{ + "component": "http", + "event": "jwt_secret_insecure", + }).Warn("AGENT_JWT_SECRET is set to the publicly known legacy default; set a random value") + } + return []byte(secret) + } + + path := filepath.Join(configDirectory, "data", "config", jwtSecretFileName) + if data, err := os.ReadFile(path); err == nil { + secret := strings.TrimSpace(string(data)) + if len(secret) >= minJWTSecretLength { + return []byte(secret) + } + log.WithFields(log.Fields{ + "component": "http", + "event": "jwt_secret_invalid", + "path": path, + }).Warn("Stored JWT secret is too short; generating a new one") + } else if !errors.Is(err, os.ErrNotExist) { + log.WithError(err).WithFields(log.Fields{ + "component": "http", + "event": "jwt_secret_read_failed", + "path": path, + }).Warn("Could not read stored JWT secret; generating a new one") + } + + secret, err := randomJWTSecret() + if err != nil { + log.WithError(err).WithFields(log.Fields{ + "component": "http", + "event": "jwt_secret_generation_failed", + }).Fatal("Could not generate a JWT signing secret") + } + + if err := writeJWTSecret(path, secret); err != nil { + log.WithError(err).WithFields(log.Fields{ + "component": "http", + "event": "jwt_secret_persist_failed", + "path": path, + }).Warn("Could not store the generated JWT secret; sessions will not survive a restart") + } else { + log.WithFields(log.Fields{ + "component": "http", + "event": "jwt_secret_generated", + "path": path, + }).Info("Generated a new JWT signing secret") + } + return []byte(secret) +} + +func randomJWTSecret() (string, error) { + buf := make([]byte, 32) + if _, err := rand.Read(buf); err != nil { + return "", err + } + return hex.EncodeToString(buf), nil +} + +func writeJWTSecret(path, secret string) error { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + tmp := path + ".tmp" + if err := os.WriteFile(tmp, []byte(secret+"\n"), 0o600); err != nil { + return err + } + return os.Rename(tmp, path) +} + +// agentUsername is the single account allowed to use the API. +func agentUsername() string { + if username := os.Getenv("AGENT_USERNAME"); username != "" { + return username + } + return "root" +} diff --git a/machinery/src/routers/http/routes.go b/machinery/src/routers/http/routes.go index 2717672..a60650d 100644 --- a/machinery/src/routers/http/routes.go +++ b/machinery/src/routers/http/routes.go @@ -18,7 +18,10 @@ func AddRoutes(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware, configDirect HealthCheck(c, communication) }) - r.GET("/ws", func(c *gin.Context) { + // The WebSocket carries the live camera stream, so it needs a token like + // the API. Browsers cannot set headers on WebSocket requests, so the UI + // passes it as the ?token= query parameter. + r.GET("/ws", authMiddleware.MiddlewareFunc(), func(c *gin.Context) { websocket.WebsocketHandler(c, configuration, communication, captureDevice) }) diff --git a/machinery/src/routers/http/security_test.go b/machinery/src/routers/http/security_test.go new file mode 100644 index 0000000..abc2c08 --- /dev/null +++ b/machinery/src/routers/http/security_test.go @@ -0,0 +1,204 @@ +package http + +import ( + "encoding/json" + stdhttp "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + jwt "github.com/appleboy/gin-jwt/v2" + "github.com/gin-gonic/gin" + jwtgo "github.com/golang-jwt/jwt/v4" + "github.com/kerberos-io/agent/machinery/src/models" +) + +func TestLoadJWTSecretPrefersEnvironment(t *testing.T) { + dir := t.TempDir() + t.Setenv("AGENT_JWT_SECRET", "shared-with-factory") + + if got := string(loadJWTSecret(dir)); got != "shared-with-factory" { + t.Fatalf("loadJWTSecret() = %q, want the AGENT_JWT_SECRET value", got) + } + if _, err := os.Stat(filepath.Join(dir, "data", "config", jwtSecretFileName)); !os.IsNotExist(err) { + t.Fatalf("no secret file should be written when AGENT_JWT_SECRET is set, stat err = %v", err) + } +} + +func TestLoadJWTSecretGeneratesAndPersistsRandomSecret(t *testing.T) { + dir := t.TempDir() + t.Setenv("AGENT_JWT_SECRET", "") + + first := string(loadJWTSecret(dir)) + if first == legacyJWTSecret || len(first) != 64 { + t.Fatalf("generated secret = %q, want 64 random hex characters", first) + } + + path := filepath.Join(dir, "data", "config", jwtSecretFileName) + info, err := os.Stat(path) + if err != nil { + t.Fatalf("secret file not written: %v", err) + } + if perm := info.Mode().Perm(); perm != 0o600 { + t.Fatalf("secret file permissions = %o, want 600", perm) + } + + if second := string(loadJWTSecret(dir)); second != first { + t.Fatalf("secret changed across restarts: %q then %q", first, second) + } + if other := string(loadJWTSecret(t.TempDir())); other == first { + t.Fatal("two installs generated the same secret") + } +} + +func TestLoadJWTSecretReplacesShortStoredSecret(t *testing.T) { + dir := t.TempDir() + t.Setenv("AGENT_JWT_SECRET", "") + path := filepath.Join(dir, "data", "config", jwtSecretFileName) + if err := writeJWTSecret(path, legacyJWTSecret); err != nil { + t.Fatal(err) + } + + got := string(loadJWTSecret(dir)) + if got == legacyJWTSecret || len(got) != 64 { + t.Fatalf("short stored secret was reused: %q", got) + } +} + +// securityRouter wires the real middleware and routes the way StartServer does. +func securityRouter(t *testing.T) (*gin.Engine, []byte) { + t.Helper() + gin.SetMode(gin.TestMode) + t.Setenv("AGENT_JWT_SECRET", "") + t.Setenv("AGENT_USERNAME", "") + t.Setenv("AGENT_PASSWORD", "") + + dir := t.TempDir() + config := JWTMiddleWare(dir) + authMiddleware, err := jwt.New(&config) + if err != nil { + t.Fatalf("initialize JWT middleware: %v", err) + } + + router := gin.New() + router.Use(gin.Recovery()) + registerProfiler(router, authMiddleware) + AddRoutes(router, authMiddleware, dir, &models.Configuration{}, &models.Communication{}, nil) + registerFileRoute(router, authMiddleware, dir, &models.Configuration{}) + return router, config.Key +} + +func signedToken(t *testing.T, key []byte, username string) string { + t.Helper() + token := jwtgo.NewWithClaims(jwtgo.SigningMethodHS256, jwtgo.MapClaims{ + "id": map[string]interface{}{"username": username, "role": "admin"}, + "exp": time.Now().Add(time.Hour).Unix(), + "orig_iat": time.Now().Unix(), + }) + signed, err := token.SignedString(key) + if err != nil { + t.Fatal(err) + } + return signed +} + +func request(router *gin.Engine, method, target, bearer string) int { + req := httptest.NewRequest(method, target, nil) + if bearer != "" { + req.Header.Set("Authorization", "Bearer "+bearer) + } + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + return rec.Code +} + +func TestAPIRejectsTokensSignedWithLegacyDefaultKey(t *testing.T) { + router, _ := securityRouter(t) + forged := signedToken(t, []byte(legacyJWTSecret), "root") + + if code := request(router, "GET", "/api/config", forged); code != stdhttp.StatusUnauthorized { + t.Fatalf("token signed with the legacy key: status %d, want 401", code) + } +} + +func TestAPIRejectsTokensForOtherUsers(t *testing.T) { + router, key := securityRouter(t) + other := signedToken(t, key, "intruder") + + if code := request(router, "GET", "/api/config", other); code != stdhttp.StatusForbidden { + t.Fatalf("validly signed token for another user: status %d, want 403", code) + } +} + +func TestLoginTokenGrantsAccess(t *testing.T) { + router, _ := securityRouter(t) + + req := httptest.NewRequest("POST", "/api/login", strings.NewReader(`{"username":"root","password":"root"}`)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + if rec.Code != stdhttp.StatusOK { + t.Fatalf("login: status %d, body %s", rec.Code, rec.Body.String()) + } + var body struct { + Token string `json:"token"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body.Token == "" { + t.Fatalf("login response without token: %s", rec.Body.String()) + } + + if code := request(router, "GET", "/file/missing.mp4?token="+body.Token, ""); code == stdhttp.StatusUnauthorized || code == stdhttp.StatusForbidden { + t.Fatalf("login token rejected on /file: status %d", code) + } +} + +func TestRecordingsRequireToken(t *testing.T) { + router, key := securityRouter(t) + + if code := request(router, "GET", "/file/recording.mp4", ""); code != stdhttp.StatusUnauthorized { + t.Fatalf("/file without token: status %d, want 401", code) + } + // With a valid token the handler runs and reports the missing file. + token := signedToken(t, key, "root") + if code := request(router, "GET", "/file/recording.mp4?token="+token, ""); code != stdhttp.StatusNotFound { + t.Fatalf("/file with ?token=: status %d, want 404 from the handler", code) + } +} + +func TestLiveWebSocketRequiresToken(t *testing.T) { + router, key := securityRouter(t) + + if code := request(router, "GET", "/ws", ""); code != stdhttp.StatusUnauthorized { + t.Fatalf("/ws without token: status %d, want 401", code) + } + // With a valid token the request reaches the upgrader, which rejects a + // non-WebSocket request itself. + token := signedToken(t, key, "root") + if code := request(router, "GET", "/ws?token="+token, ""); code == stdhttp.StatusUnauthorized || code == stdhttp.StatusForbidden { + t.Fatalf("/ws with ?token=: status %d, want the request to pass authentication", code) + } +} + +func TestProfilerDisabledByDefault(t *testing.T) { + t.Setenv("AGENT_ENABLE_PPROF", "") + router, key := securityRouter(t) + + if code := request(router, "GET", "/debug/pprof/", signedToken(t, key, "root")); code != stdhttp.StatusNotFound { + t.Fatalf("pprof without AGENT_ENABLE_PPROF: status %d, want 404", code) + } +} + +func TestProfilerRequiresTokenWhenEnabled(t *testing.T) { + t.Setenv("AGENT_ENABLE_PPROF", "true") + router, key := securityRouter(t) + + if code := request(router, "GET", "/debug/pprof/", ""); code != stdhttp.StatusUnauthorized { + t.Fatalf("enabled pprof without token: status %d, want 401", code) + } + if code := request(router, "GET", "/debug/pprof/", signedToken(t, key, "root")); code != stdhttp.StatusOK { + t.Fatalf("enabled pprof with token: status %d, want 200", code) + } +} diff --git a/machinery/src/routers/http/server.go b/machinery/src/routers/http/server.go index 83917d2..0402e81 100644 --- a/machinery/src/routers/http/server.go +++ b/machinery/src/routers/http/server.go @@ -61,17 +61,14 @@ func StartServer(configDirectory string, configuration *models.Configuration, co c.AbortWithStatus(500) })) - // Profiler - pprof.Register(r) - // Setup CORS r.Use(CORS()) // Add Swagger r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) - // The JWT middlewareergreggre - middleWare := JWTMiddleWare() + // The JWT middleware + middleWare := JWTMiddleWare(configDirectory) authMiddleware, err := jwt.New(&middleWare) if err != nil { log.WithError(err).WithFields(log.Fields{ @@ -80,6 +77,8 @@ func StartServer(configDirectory string, configuration *models.Configuration, co }).Fatal("Failed to initialize JWT middleware") } + registerProfiler(r, authMiddleware) + // Add all routes AddRoutes(r, authMiddleware, configDirectory, configuration, communication, captureDevice) @@ -103,9 +102,7 @@ func StartServer(configDirectory string, configuration *models.Configuration, co r.Use(static.Serve("/media", static.LocalFile(configDirectory+"/www", true))) r.Use(static.Serve("/settings", static.LocalFile(configDirectory+"/www", true))) r.Use(static.Serve("/login", static.LocalFile(configDirectory+"/www", true))) - r.Handle("GET", "/file/*filepath", func(c *gin.Context) { - Files(c, configDirectory, configuration) - }) + registerFileRoute(r, authMiddleware, configDirectory, configuration) // Run the api on port log.WithFields(log.Fields{ @@ -123,6 +120,23 @@ func StartServer(configDirectory string, configuration *models.Configuration, co } } +// registerProfiler exposes the Go profiler only when AGENT_ENABLE_PPROF=true. +// The endpoints expose heap dumps (which can contain credentials) and can be +// used to exhaust the CPU, so they always require a valid token. +func registerProfiler(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) { + if os.Getenv("AGENT_ENABLE_PPROF") == "true" { + pprof.Register(r.Group("", authMiddleware.MiddlewareFunc())) + } +} + +// registerFileRoute serves recordings to signed-in users. Browsers load them +// through