Skip to content

refactor: move federated server logic to its own service#3

Open
DhirenMhatre wants to merge 1 commit into
masterfrom
fed_refactor
Open

refactor: move federated server logic to its own service#3
DhirenMhatre wants to merge 1 commit into
masterfrom
fed_refactor

Conversation

@DhirenMhatre

Copy link
Copy Markdown

No description provided.

Signed-off-by: Ettore Di Giacinto <mudler@localai.io>
@codity-dm

codity-dm Bot commented May 16, 2026

Copy link
Copy Markdown

Policy Check Failed

✗ 3/3 policy checks failed:

• Need 2 more approval(s) (0/2) — comment LGTM or approve via review
• Missing ticket reference (expected: JIRA-, ENG-, #*)
• 5 code file(s) changed but no test files added


To merge this PR:

  1. Address the failed checks listed above
  2. Ensure branch protection requires the codity/policy-check status

Configure policies in your dashboard

@codity-dm

codity-dm Bot commented May 16, 2026

Copy link
Copy Markdown

PR Summary

What Changed

  • Extracted P2P federated server logic into a dedicated FederatedServer struct and moved implementation to core/p2p/federation.go.
  • Simplified core/cli/federated.go to delegate to FederatedServer.Start() instead of implementing proxy logic inline.
  • Moved handleConn() and copyStream() helpers to federation.go to support connection forwarding via tunnel addresses.

Key Changes by Area

P2P Architecture: Introduced FederatedServer struct in core/p2p/federatedServer.go to encapsulate federated server state and behavior.
CLI Integration: Updated core/cli/federated.go to instantiate and invoke FederatedServer.Start() instead of running proxy logic directly.
Helper Functions: Relocated handleConn() and copyStream() from p2p.go to federation.go for better cohesion.

Files Changed

File Changes Summary
core/cli/federated.go Simplified to instantiate and call FederatedServer.Start()
core/p2p/federatedServer.go Added new struct definition for FederatedServer
core/p2p/federation.go Implemented Start(), handleConn(), and copyStream()
core/p2p/p2p.go Removed handleConn() and copyStream() functions
core/p2p/p2p_disabled.go Added stub Start() method for disabled P2P builds

Review Focus Areas

  • Verify FederatedServer.Start() handles all edge cases previously covered in core/cli/federated.go.
  • Confirm copyStream() behavior remains unchanged after moving to federation.go.
  • Check that the disabled P2P build tag stub in p2p_disabled.go compiles and fails gracefully.

Architecture

Design Decisions: The refactor isolates federation concerns into a dedicated type, improving separation of concerns. Moving copyStream() and handleConn() into federation.go groups related functionality, even though copyStream() is generic—it stays here to avoid exposing internal proxy details elsewhere.

Scalability & Extensibility: The FederatedServer struct makes it easier to add new federation-related methods or configuration later. The current design keeps federation logic self-contained but does not yet support pluggable backends or multiple federation modes.

Risks: The copyStream() function is now used only within federation.go. If future changes require reuse elsewhere, duplication may occur unless refactored again. This is acceptable for now but worth noting.

@greptile-apps

greptile-apps Bot commented May 16, 2026

Copy link
Copy Markdown

Greptile Summary

This PR extracts the federated-server proxy logic out of core/cli/federated.go into a dedicated FederatedServer service type living in the p2p package, and provides matching build-tag–gated implementations (federation.go for p2p builds, p2p_disabled.go stub for non-p2p builds).

  • federatedServer.go introduces the FederatedServer struct and constructor (no build tag, correctly shared by both build variants); federation.go (p2p-only) contains the real Start, proxy, and handleConn implementation migrated from the old CLI file.
  • handleConn carries forward a latent panic: when all federated nodes are offline tunnelAddresses is empty and rand.IntN(0) panics instead of returning a clean error; a nil-length guard is missing.
  • FederatedServer.Start starts the underlying p2p node directly, then calls ServiceDiscoverer which internally calls discoveryTunnels — that function also calls n.Start(ctx) on the same node instance, producing a double-start on every federated server launch.

Confidence Score: 3/5

The refactoring cleanly separates the federated-server concern, but two runtime correctness issues in the new federation.go file should be resolved before merging.

The empty-slice panic in handleConn is a real crash path that fires whenever a client connects while no online nodes have been discovered yet. The double node.Start call is inherited from the original code but now codified in the new service.

core/p2p/federation.go needs attention for the empty-tunnel-address panic in handleConn and the double Start call sequence.

Important Files Changed

Filename Overview
core/p2p/federation.go New file hosting the p2p-enabled FederatedServer.Start and proxy logic; contains a panic-inducing empty-slice index in handleConn and a double node.Start call.
core/p2p/federatedServer.go New struct definition and constructor for FederatedServer; no build tag needed as the type must be visible to both the p2p and !p2p stub implementations.
core/cli/federated.go CLI entry point trimmed to delegate to the new FederatedServer; logic moved correctly to the p2p package.
core/p2p/p2p.go copyStream removed (moved to federation.go); the remaining allocateLocalService still references it, which compiles correctly because both files share the p2p build tag.
core/p2p/p2p_disabled.go Stub Start method added for the !p2p build; correctly returns 'not implemented' to mirror the pattern used by other stubs in this file.

Sequence Diagram

sequenceDiagram
    participant CLI as FederatedCLI.Run
    participant FS as FederatedServer
    participant Node as p2p Node
    participant SD as ServiceDiscoverer
    participant DT as discoveryTunnels
    participant HC as handleConn

    CLI->>FS: NewFederatedServer(addr, FederatedID, token)
    CLI->>FS: Start(ctx)
    FS->>Node: NewNode(token)
    FS->>Node: n.Start(ctx) first Start
    FS->>SD: ServiceDiscoverer(ctx, n, token, FederatedID, nil)
    SD->>DT: discoveryTunnels(ctx, n, token, servicesID)
    DT->>Node: n.Start(ctx) second Start
    DT-->>SD: chan NodeData
    SD-->>FS: nil
    FS->>FS: proxy(ctx, n)
    loop accept connections
        FS->>FS: l.Accept()
        FS->>HC: go handleConn(conn)
        HC->>HC: GetAvailableNodes(FederatedID)
        alt tunnelAddresses empty
            HC-->>HC: PANIC rand.IntN(0)
        else at least one online node
            HC->>HC: rand pick tunnel address
            HC->>HC: net.Dial(tunnelAddr)
            HC->>HC: copyStream bidirectional
        end
    end
Loading

Reviews (1): Last reviewed commit: "refactor: move federated server logic to..." | Re-trigger Greptile

Comment thread core/p2p/federation.go
// open a TCP stream to one of the tunnels
// chosen randomly
// TODO: optimize this and track usage
tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Panic when no online nodes are available

If all federated nodes are offline, tunnelAddresses is empty and rand.IntN(0) panics at runtime. The refactoring extracted this into a standalone handleConn function, preserving the crash path. Any incoming connection when the cluster has no live members will terminate the goroutine with a panic rather than returning a clean error to the caller.

Comment thread core/p2p/federation.go
Comment on lines +28 to +33
err = n.Start(ctx)
if err != nil {
return fmt.Errorf("starting a new node: %w", err)
}

if err := ServiceDiscoverer(ctx, n, fs.p2ptoken, FederatedID, nil); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Node started twice before service discovery

FederatedServer.Start calls n.Start(ctx) on line 28, then ServiceDiscovererdiscoveryTunnels (in p2p.go) calls n.Start(ctx) a second time on the same node instance. This mirrors the original FederatedCLI.Run behaviour but is carried forward here. Depending on how edgevpn's node.Start handles duplicate calls (panic, error, or silent no-op), this could result in unexpected runtime behaviour.

Comment thread core/p2p/federation.go
Comment on lines +103 to +106
// open a TCP stream to one of the tunnels
// chosen randomly
// TODO: optimize this and track usage
tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 After collecting online addresses, add a guard before calling rand.IntN so an empty slice does not cause a panic. The connection should be closed cleanly with a log message instead.

Suggested change
// open a TCP stream to one of the tunnels
// chosen randomly
// TODO: optimize this and track usage
tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]
// open a TCP stream to one of the tunnels
// chosen randomly
// TODO: optimize this and track usage
if len(tunnelAddresses) == 0 {
log.Error().Msg("No online tunnel nodes available")
conn.Close()
return
}
tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

Comment thread core/p2p/federation.go
// open a TCP stream to one of the tunnels
// chosen randomly
// TODO: optimize this and track usage
tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional Critical

If tunnelAddresses is empty (no online nodes), rand.IntN(0) panics with a runtime error; add a guard before indexing.

Suggested fix
	if len(tunnelAddresses) == 0 {
		log.Error().Msg("No online tunnel nodes available")
		conn.Close()
		return
	}
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 106-106
Issue Type: functional-critical
Severity: critical

Issue Description:
If `tunnelAddresses` is empty (no online nodes), `rand.IntN(0)` panics with a runtime error; add a guard before indexing.

Current Code:
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/cli/federated.go
func copyStream(closer chan struct{}, dst io.Writer, src io.Reader) {
defer func() { closer <- struct{}{} }() // connection is closed, send signal to stop proxy
io.Copy(dst, src)
return fs.Start(context.Background())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional High

The new code passes context.Background() instead of the CLI-provided context, so cancellation signals (e.g., SIGINT) from the caller are ignored and the server cannot be gracefully shut down.

Suggested change
return fs.Start(context.Background())
return fs.Start(ctx.Context)
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/cli/federated.go
Lines: 18-18
Issue Type: functional-high
Severity: high

Issue Description:
The new code passes `context.Background()` instead of the CLI-provided context, so cancellation signals (e.g., SIGINT) from the caller are ignored and the server cannot be gracefully shut down.

Current Code:
	return fs.Start(context.Background())

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment on lines +7 to +13
func NewFederatedServer(listenAddr, service, p2pToken string) *FederatedServer {
return &FederatedServer{
listenAddr: listenAddr,
service: service,
p2ptoken: p2pToken,
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Security High

The p2p token is stored as a plain string field with no validation or sanitization; an empty or malformed token passed to NewFederatedServer will propagate silently and be used to initialize a network node, potentially allowing unauthenticated federation. Add a non-empty check and return an error or panic early.

Suggested fix
func NewFederatedServer(listenAddr, service, p2pToken string) (*FederatedServer, error) {
	if p2pToken == "" {
		return nil, fmt.Errorf("p2pToken must not be empty")
	}
	if listenAddr == "" {
		return nil, fmt.Errorf("listenAddr must not be empty")
	}
	return &FederatedServer{
		listenAddr: listenAddr,
		service:    service,
		p2ptoken:   p2pToken,
	}, nil
}
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federatedServer.go
Lines: 7-13
Issue Type: security-high
Severity: high

Issue Description:
The p2p token is stored as a plain string field with no validation or sanitization; an empty or malformed token passed to NewFederatedServer will propagate silently and be used to initialize a network node, potentially allowing unauthenticated federation. Add a non-empty check and return an error or panic early.

Current Code:
func NewFederatedServer(listenAddr, service, p2pToken string) *FederatedServer {
	return &FederatedServer{
		listenAddr: listenAddr,
		service:    service,
		p2ptoken:   p2pToken,
	}
}

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/p2p/federation.go
}
// ll.Info("Binding local port on", srcaddr)

ledger, _ := node.Ledger()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness High

The error returned by node.Ledger() is silently discarded with _; a nil ledger will cause a nil-pointer panic on the subsequent ledger.Announce call.

Suggested fix
	ledger, err := node.Ledger()
	if err != nil {
		log.Error().Err(err).Msg("Error getting ledger")
		return err
	}
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 51-51
Issue Type: robustness-high
Severity: high

Issue Description:
The error returned by `node.Ledger()` is silently discarded with `_`; a nil ledger will cause a nil-pointer panic on the subsequent `ledger.Announce` call.

Current Code:
	ledger, _ := node.Ledger()

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/p2p/federation.go
Comment on lines +97 to +108
tunnelAddresses = append(tunnelAddresses, v.TunnelAddress)
} else {
log.Info().Msgf("Node %s is offline", v.ID)
}
}

// open a TCP stream to one of the tunnels
// chosen randomly
// TODO: optimize this and track usage
tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

tunnelConn, err := net.Dial("tcp", tunnelAddr)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Security High

TunnelAddress values sourced from the distributed ledger (untrusted peers) are passed directly to net.Dial without validation, allowing a malicious peer to redirect connections to arbitrary internal hosts (SSRF).

Suggested fix
			// Validate that tunnelAddr resolves to an expected loopback/VPN range before dialing.
			// Example: parse host and verify it is within the allowed CIDR before appending.
					host, _, err := net.SplitHostPort(v.TunnelAddress)
					if err != nil {
						log.Warn().Msgf("Skipping invalid tunnel address %s", v.TunnelAddress)
						continue
					}
					ip := net.ParseIP(host)
					if ip == nil || !allowedCIDR.Contains(ip) {
						log.Warn().Msgf("Tunnel address %s outside allowed range, skipping", v.TunnelAddress)
						continue
					}
					tunnelAddresses = append(tunnelAddresses, v.TunnelAddress)
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 97-108
Issue Type: security-high
Severity: high

Issue Description:
`TunnelAddress` values sourced from the distributed ledger (untrusted peers) are passed directly to `net.Dial` without validation, allowing a malicious peer to redirect connections to arbitrary internal hosts (SSRF).

Current Code:
			tunnelAddresses = append(tunnelAddresses, v.TunnelAddress)
		}
	}

	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

	tunnelConn, err := net.Dial("tcp", tunnelAddr)

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/p2p/federation.go
Comment on lines +73 to +89
for {
select {
case <-ctx.Done():
return errors.New("context canceled")
default:
log.Debug().Msg("New for connection")
// Listen for an incoming connection.
conn, err := l.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
continue
}

// Handle connections in a new goroutine, forwarding to the p2p service
go handleConn(conn)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance High

The proxy accept loop spins in the default branch without blocking, consuming 100% CPU when no connections arrive; l.Accept() already blocks, but the surrounding select with a default case means the goroutine never yields to the scheduler between the context check and the blocking Accept call on a busy loop iteration: replace with a blocking accept and a separate context-cancellation mechanism.

Suggested fix
	go func() {
		<-ctx.Done()
		l.Close()
	}()
	for {
		conn, err := l.Accept()
		if err != nil {
			select {
			case <-ctx.Done():
				return errors.New("context canceled")
			default:
				log.Error().Err(err).Msg("Error accepting")
				continue
			}
		}
		go handleConn(conn)
	}
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 73-89
Issue Type: performance-high
Severity: high

Issue Description:
The `proxy` accept loop spins in the `default` branch without blocking, consuming 100% CPU when no connections arrive; `l.Accept()` already blocks, but the surrounding `select` with a `default` case means the goroutine never yields to the scheduler between the context check and the blocking `Accept` call on a busy loop iteration: replace with a blocking accept and a separate context-cancellation mechanism.

Current Code:
	for {
		select {
		case <-ctx.Done():
			return errors.New("context canceled")
		default:
			log.Debug().Msg("New for connection")
			conn, err := l.Accept()
			if err != nil {
				fmt.Println("Error accepting: ", err.Error())
				continue
			}
			go handleConn(conn)
		}
	}

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/p2p/federation.go
Comment on lines +124 to +127
func copyStream(closer chan struct{}, dst io.Writer, src io.Reader) {
defer func() { closer <- struct{}{} }() // connection is closed, send signal to stop proxy
io.Copy(dst, src)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness Medium

io.Copy errors are silently ignored in copyStream; log or surface the error so connection failures are observable.

Suggested fix
func copyStream(closer chan struct{}, dst io.Writer, src io.Reader) {
	defer func() { closer <- struct{}{} }() // connection is closed, send signal to stop proxy
	if _, err := io.Copy(dst, src); err != nil {
		log.Debug().Err(err).Msg("copyStream error")
	}
}
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 124-127
Issue Type: robustness-medium
Severity: medium

Issue Description:
`io.Copy` errors are silently ignored in `copyStream`; log or surface the error so connection failures are observable.

Current Code:
func copyStream(closer chan struct{}, dst io.Writer, src io.Reader) {
	defer func() { closer <- struct{}{} }() // connection is closed, send signal to stop proxy
	io.Copy(dst, src)
}

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

@codity-dm

codity-dm Bot commented May 16, 2026

Copy link
Copy Markdown

Security Scan

Security scan in progress...

Analyzing code for:

  • Hardcoded secrets and credentials
  • Injection vulnerabilities (SQL, Command, XSS)
  • Authentication and authorization issues
  • Cryptographic weaknesses

Results will be posted shortly...

@DhirenMhatre

Copy link
Copy Markdown
Author

@codity review

@codity-dm

codity-dm Bot commented May 16, 2026

Copy link
Copy Markdown

Policy Check Failed

✗ 3/3 policy checks failed:

• Need 2 more approval(s) (0/2) — comment LGTM or approve via review
• Missing ticket reference (expected: JIRA-, ENG-, #*)
• 5 code file(s) changed but no test files added


To merge this PR:

  1. Address the failed checks listed above
  2. Ensure branch protection requires the codity/policy-check status

Configure policies in your dashboard

@codity-dm

codity-dm Bot commented May 16, 2026

Copy link
Copy Markdown

PR Summary

What Changed

  • Extracted P2P federated server logic into a dedicated FederatedServer struct and new federation.go file to improve modularity.
  • Simplified core/cli/federated.go to delegate server startup to FederatedServer.Start() instead of implementing proxy logic inline.
  • Moved copyStream() and added handleConn() to federation.go to centralize connection forwarding logic.

Key Changes by Area

P2P Architecture: Introduced FederatedServer struct in core/p2p/federatedServer.go to encapsulate federated server state and behavior.

CLI Integration: Updated core/cli/federated.go to instantiate and start FederatedServer instead of handling proxy setup directly.

Build Tags: Added a stub Start() method in core/p2p/p2p_disabled.go for builds with the p2p tag disabled.

Files Changed

File Changes Summary
core/cli/federated.go Removed inline proxy setup logic; now calls fs.Start() on a FederatedServer instance.
core/p2p/federatedServer.go New file defining the FederatedServer struct with fields for config and services.
core/p2p/federation.go New file implementing FederatedServer.Start(), handleConn(), and copyStream().
core/p2p/p2p.go Removed copyStream() helper function (moved to federation.go).
core/p2p/p2p_disabled.go Added disabled P2P stub for FederatedServer.Start() to satisfy build constraints.

Review Focus Areas

  • Verify FederatedServer.Start() handles all error paths and cleanup correctly, especially around service discovery and proxy setup.
  • Confirm handleConn() properly closes connections and streams on errors to avoid resource leaks.
  • Check that the disabled P2P stub in p2p_disabled.go matches the signature and behavior expectations for conditional builds.

Architecture

Design Decisions: The refactor isolates federated server concerns into a dedicated type, making the CLI command a thin wrapper. This separates concerns and improves testability. Moving copyStream() to federation.go groups related networking logic together.

Scalability & Extensibility: The FederatedServer struct provides a natural extension point for future features like metrics or lifecycle hooks. The current design keeps the CLI agnostic of internal implementation details.

Risks: The FederatedServer type now holds shared state (e.g., service discovery client). Reviewers should confirm that concurrent access is properly synchronized if multiple goroutines call methods on the same instance. This risk is intentional and acceptable if the CLI only starts one instance per process.

Comment thread core/p2p/federation.go
// open a TCP stream to one of the tunnels
// chosen randomly
// TODO: optimize this and track usage
tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional Critical

If tunnelAddresses is empty, rand.IntN(0) panics with a runtime error; add a guard to close the connection and return early when no online nodes are available.

Suggested fix
	if len(tunnelAddresses) == 0 {
		log.Error().Msg("No online tunnel nodes available")
		conn.Close()
		return
	}
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 106-106
Issue Type: functional-critical
Severity: critical

Issue Description:
If `tunnelAddresses` is empty, `rand.IntN(0)` panics with a runtime error; add a guard to close the connection and return early when no online nodes are available.

Current Code:
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/cli/federated.go
func copyStream(closer chan struct{}, dst io.Writer, src io.Reader) {
defer func() { closer <- struct{}{} }() // connection is closed, send signal to stop proxy
io.Copy(dst, src)
return fs.Start(context.Background())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness High

The new code passes context.Background() instead of the CLI-provided context, so cancellation signals (e.g., SIGINT) from the caller are ignored and the server cannot be gracefully shut down.

Suggested change
return fs.Start(context.Background())
return fs.Start(ctx.Context)
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/cli/federated.go
Lines: 18-18
Issue Type: robustness-high
Severity: high

Issue Description:
The new code passes `context.Background()` instead of the CLI-provided context, so cancellation signals (e.g., SIGINT) from the caller are ignored and the server cannot be gracefully shut down.

Current Code:
	return fs.Start(context.Background())

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/p2p/federation.go
}
// ll.Info("Binding local port on", srcaddr)

ledger, _ := node.Ledger()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness High

The error from node.Ledger() is silently discarded with _; if ledger acquisition fails, subsequent calls on the nil ledger will panic.

Suggested fix
	ledger, err := node.Ledger()
	if err != nil {
		log.Error().Err(err).Msg("Error getting ledger")
		return err
	}
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 51-51
Issue Type: robustness-high
Severity: high

Issue Description:
The error from `node.Ledger()` is silently discarded with `_`; if ledger acquisition fails, subsequent calls on the nil ledger will panic.

Current Code:
	ledger, _ := node.Ledger()

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/p2p/federation.go
Comment on lines +73 to +89
for {
select {
case <-ctx.Done():
return errors.New("context canceled")
default:
log.Debug().Msg("New for connection")
// Listen for an incoming connection.
conn, err := l.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
continue
}

// Handle connections in a new goroutine, forwarding to the p2p service
go handleConn(conn)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness Medium

When l.Accept() returns an error after context cancellation, the loop continues to the default branch and calls l.Accept() again instead of exiting; check ctx.Done() before retrying or use a non-blocking select with a timeout.

Suggested fix
	for {
		select {
		case <-ctx.Done():
			return errors.New("context canceled")
		default:
		}
		log.Debug().Msg("New for connection")
		conn, err := l.Accept()
		if err != nil {
			select {
			case <-ctx.Done():
				return errors.New("context canceled")
			default:
			}
			log.Error().Err(err).Msg("Error accepting connection")
			continue
		}
		go handleConn(conn)
	}
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 73-89
Issue Type: robustness-medium
Severity: medium

Issue Description:
When `l.Accept()` returns an error after context cancellation, the loop continues to the `default` branch and calls `l.Accept()` again instead of exiting; check `ctx.Done()` before retrying or use a non-blocking select with a timeout.

Current Code:
	for {
		select {
		case <-ctx.Done():
			return errors.New("context canceled")
		default:
			log.Debug().Msg("New for connection")
			conn, err := l.Accept()
			if err != nil {
				fmt.Println("Error accepting: ", err.Error())
				continue
			}
			go handleConn(conn)
		}
	}

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/cli/federated.go

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Security Critical

In federation.go handleConn, if tunnelAddresses is empty (no online nodes), rand.IntN(0) panics with a divide-by-zero, crashing the goroutine and potentially the process; add a length check and close the connection before returning.

Suggested fix
	if len(tunnelAddresses) == 0 {
		log.Error().Msg("No online tunnel nodes available")
		conn.Close()
		return
	}
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/cli/federated.go
Lines: 100-104
Issue Type: security-critical
Severity: critical

Issue Description:
In `federation.go` `handleConn`, if `tunnelAddresses` is empty (no online nodes), `rand.IntN(0)` panics with a divide-by-zero, crashing the goroutine and potentially the process; add a length check and close the connection before returning.

Current Code:
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

@codity-dm

codity-dm Bot commented May 16, 2026

Copy link
Copy Markdown

Security Scan Summary

Metric Value
Vulnerabilities Critical: 0
Overall Risk Medium
Files Scanned 5

Consider addressing security findings before merging

Scan completed in 37.7s

View vulnerability details (2 items)

1. MATH_RANDOM_USED (CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)) HIGH

File: core/p2p/federation.go (line 16)
Category: Other

Do not use math/rand. Use crypto/rand instead.

Fix: Review and fix the security issue following OWASP guidelines.


2. SEC-400 (CWE-400) MEDIUM

File: core/p2p/federation.go (line 105)
Category: Other

tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

The proxy handler selects a random tunnel address with rand.IntN(len(tunnelAddresses)) without checking whether any tunnels are available. When the P2P network has no online nodes, len(tunnelAddresses) will be zero and this call will panic, crashing the federated server. An unauthenticated connection to the exposed listener while no peers are available can therefore trigger a denial of service.

Fix: Before calling rand.IntN, verify that tunnelAddresses is not empty. If no peers are available, reject the connection or wait until one is available instead of panicking.


Security scan powered by Codity.ai

@DhirenMhatre

Copy link
Copy Markdown
Author

@codity review

@codity-dm

codity-dm Bot commented May 17, 2026

Copy link
Copy Markdown

Policy Check Failed

✗ 3/3 policy checks failed:

• Need 2 more approval(s) (0/2) — comment LGTM or approve via review
• Missing ticket reference (expected: JIRA-, ENG-, #*)
• 5 code file(s) changed but no test files added


To merge this PR:

  1. Address the failed checks listed above
  2. Ensure branch protection requires the codity/policy-check status

Configure policies in your dashboard

@DhirenMhatre

Copy link
Copy Markdown
Author

@codity review

@codity-dm

codity-dm Bot commented May 17, 2026

Copy link
Copy Markdown

Policy Check Failed

✗ 3/3 policy checks failed:

• Need 2 more approval(s) (0/2) — comment LGTM or approve via review
• Missing ticket reference (expected: JIRA-, ENG-, #*)
• 5 code file(s) changed but no test files added


To merge this PR:

  1. Address the failed checks listed above
  2. Ensure branch protection requires the codity/policy-check status

Configure policies in your dashboard

@codity-dm

codity-dm Bot commented May 17, 2026

Copy link
Copy Markdown

PR Summary

What Changed

  • Extracted federated server proxy logic from CLI into a new FederatedServer struct in the core/p2p package.
  • Added build tag support to conditionally compile P2P federation code.
  • Removed duplicate copyStream() helper from p2p.go after consolidating in federation.go.

Key Changes by Area

P2P Core: New FederatedServer struct encapsulates server config and proxy handling. Moved Start(), proxy(), and handleConn() methods from CLI to dedicated federation.go.

CLI: core/cli/federated.go reduced from ~110 lines to ~20 lines by delegating to FederatedServer.

Build System: Added //go:build p2p constraint to federation code with stub fallback in p2p_disabled.go for P2P-disabled builds.

Files Changed

File Changes Summary
core/cli/federated.go Simplified to delegate server startup to FederatedServer
core/p2p/federatedServer.go New struct definition for server configuration
core/p2p/federation.go New file with extracted proxy logic and copyStream() helper
core/p2p/p2p.go Removed duplicate copyStream() function
core/p2p/p2p_disabled.go New stub implementation for non-P2P builds

Review Focus Areas

  • Build tag correctness: verify p2p_disabled.go provides compatible stubs for all exported symbols.
  • Error handling in federation.go:handleConn() and proxy() methods during connection teardown.
  • Ensure no behavioral changes in proxy stream copying after copyStream() consolidation.

Architecture

Design Decisions: The extraction intentionally keeps FederatedServer simple (config holder with Start() method) rather than introducing interfaces or abstractions. The build tag split accepts maintenance overhead of parallel stub files to support P2P-disabled builds without conditional compilation complexity at call sites.

Risks: (Intentional) p2p_disabled.go must be manually kept in sync with federation.go exports. (Unintentional) copyStream() error handling changed from original implementation. Verify no goroutine leaks in connection shutdown paths.

Comment thread core/p2p/federation.go
// open a TCP stream to one of the tunnels
// chosen randomly
// TODO: optimize this and track usage
tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional Critical

tunnelAddresses may be empty when no nodes are online, causing rand.IntN(0) to panic with an index-out-of-range; add a guard before indexing.

Suggested fix
	if len(tunnelAddresses) == 0 {
		log.Error().Msg("No online tunnel nodes available")
		conn.Close()
		return
	}
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 106-106
Issue Type: functional-critical
Severity: critical

Issue Description:
`tunnelAddresses` may be empty when no nodes are online, causing `rand.IntN(0)` to panic with an index-out-of-range; add a guard before indexing.

Current Code:
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/cli/federated.go
func copyStream(closer chan struct{}, dst io.Writer, src io.Reader) {
defer func() { closer <- struct{}{} }() // connection is closed, send signal to stop proxy
io.Copy(dst, src)
return fs.Start(context.Background())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional High

The Run method ignores the incoming ctx parameter and passes context.Background() to fs.Start, preventing proper cancellation or shutdown propagation from the CLI framework.

Suggested change
return fs.Start(context.Background())
return fs.Start(ctx.Context)
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/cli/federated.go
Lines: 18-18
Issue Type: functional-high
Severity: high

Issue Description:
The `Run` method ignores the incoming `ctx` parameter and passes `context.Background()` to `fs.Start`, preventing proper cancellation or shutdown propagation from the CLI framework.

Current Code:
	return fs.Start(context.Background())

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/p2p/federation.go
}
// ll.Info("Binding local port on", srcaddr)

ledger, _ := node.Ledger()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness High

The error return from node.Ledger() is silently discarded; if ledger acquisition fails, subsequent calls on a nil ledger will panic.

Suggested fix
	ledger, err := node.Ledger()
	if err != nil {
		return fmt.Errorf("getting ledger: %w", err)
	}
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 51-51
Issue Type: robustness-high
Severity: high

Issue Description:
The error return from `node.Ledger()` is silently discarded; if ledger acquisition fails, subsequent calls on a nil ledger will panic.

Current Code:
	ledger, _ := node.Ledger()

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/p2p/federation.go
Comment on lines +108 to +112
tunnelConn, err := net.Dial("tcp", tunnelAddr)
if err != nil {
log.Error().Err(err).Msg("Error connecting to tunnel")
return
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness High

When handleConn returns early after a dial error, conn is never closed, leaking the accepted connection.

Suggested fix
	tunnelConn, err := net.Dial("tcp", tunnelAddr)
	if err != nil {
		log.Error().Err(err).Msg("Error connecting to tunnel")
		conn.Close()
		return
	}
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 108-112
Issue Type: robustness-high
Severity: high

Issue Description:
When `handleConn` returns early after a dial error, `conn` is never closed, leaking the accepted connection.

Current Code:
	tunnelConn, err := net.Dial("tcp", tunnelAddr)
	if err != nil {
		log.Error().Err(err).Msg("Error connecting to tunnel")
		return
	}

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/p2p/federation.go
Comment on lines +73 to +89
for {
select {
case <-ctx.Done():
return errors.New("context canceled")
default:
log.Debug().Msg("New for connection")
// Listen for an incoming connection.
conn, err := l.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
continue
}

// Handle connections in a new goroutine, forwarding to the p2p service
go handleConn(conn)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness Medium

l.Accept() blocks indefinitely in the default branch, so the ctx.Done() case is never reached while waiting for a connection; use a deadline or a separate goroutine to make context cancellation responsive.

Suggested fix
	go func() {
		<-ctx.Done()
		l.Close()
	}()
	for {
		conn, err := l.Accept()
		if err != nil {
			select {
			case <-ctx.Done():
				return errors.New("context canceled")
			default:
				log.Error().Err(err).Msg("Error accepting")
				continue
			}
		}
		go handleConn(conn)
	}
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 73-89
Issue Type: robustness-medium
Severity: medium

Issue Description:
`l.Accept()` blocks indefinitely in the `default` branch, so the `ctx.Done()` case is never reached while waiting for a connection; use a deadline or a separate goroutine to make context cancellation responsive.

Current Code:
	for {
		select {
		case <-ctx.Done():
			return errors.New("context canceled")
		default:
			log.Debug().Msg("New for connection")
			// Listen for an incoming connection.
			conn, err := l.Accept()
			if err != nil {
				fmt.Println("Error accepting: ", err.Error())
				continue
			}
			// Handle connections in a new goroutine, forwarding to the p2p service
			go handleConn(conn)
		}
	}

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

@codity-dm

codity-dm Bot commented May 17, 2026

Copy link
Copy Markdown

Security Scan Summary

Metric Value
Vulnerabilities Critical: 0
Overall Risk Medium
Files Scanned 5

Consider addressing security findings before merging

Scan completed in 22.1s

View vulnerability details (1 items)

1. MATH_RANDOM_USED (CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)) HIGH

File: core/p2p/federation.go (line 16)
Category: Other

Do not use math/rand. Use crypto/rand instead.

Fix: Review and fix the security issue following OWASP guidelines.


Security scan powered by Codity.ai

@codity-dm

codity-dm Bot commented May 17, 2026

Copy link
Copy Markdown

Dependency vulnerability scanning

Metric Value
Vulnerabilities Found 171
Scanner govulncheck
Top 10 Vulnerabilities (171 total found)

1. stdlib < 1.16.1

CVE: GO-2021-0067
Fixed in: See OSV advisory

Panic when opening archives in archive/zip


2. stdlib < 1.15.5

CVE: GO-2021-0069
Fixed in: See OSV advisory

Panic during division of very large numbers in math/big


3. stdlib < 1.14.7

CVE: GO-2021-0142
Fixed in: See OSV advisory

Unbounded read from invalid inputs in encoding/binary


4. stdlib < 1.3.2

CVE: GO-2021-0154
Fixed in: See OSV advisory

Man-in-the-middle attack with SessionTicketsDisabled in crypto/tls


5. stdlib < 1.4.3

CVE: GO-2021-0159
Fixed in: See OSV advisory

Request smuggling due to improper header parsing in net/http


6. stdlib < 1.5.3

CVE: GO-2021-0160
Fixed in: See OSV advisory

Incorrect calculation affecting RSA computations in math/big


7. stdlib < 1.6.1

CVE: GO-2021-0163
Fixed in: See OSV advisory

Privilege escalation on Windows via malicious DLL in syscall


8. stdlib < 1.7.4

CVE: GO-2021-0172
Fixed in: See OSV advisory

Denial of service when parsing large forms in mime/multipart


9. stdlib < 1.9.1

CVE: GO-2021-0178
Fixed in: See OSV advisory

Cleartext transmission of credentials in net/smtp


10. stdlib < 1.14.5

CVE: GO-2021-0223
Fixed in: See OSV advisory

Certificate verification error on Windows in crypto/x509


161 more vulnerabilities not shown. Update dependencies to fix these issues.

Powered by Codity.ai · Docs

@codity-dm

codity-dm Bot commented May 17, 2026

Copy link
Copy Markdown

Dependency vulnerability scanning

Metric Value
Vulnerabilities Found 4
Scanner pip-audit
View vulnerability details (4 items)

1. pip 24.0

CVE: GHSA-4xh5-x5gv-qwph
Fixed in: 25.3

When extracting a tar archive pip may not check symbolic links point into the extraction directory if the tarfile module doesn't implement PEP 706. Note that upgrading pip to a "fixed" version for thi


2. pip 24.0

CVE: GHSA-6vgw-5pg2-w6jp
Fixed in: 26.0

When pip is installing and extracting a maliciously crafted wheel archive, files may be extracted outside the installation directory. The path traversal is limited to prefixes of the installation dire


3. pip 24.0

CVE: GHSA-58qw-9mgm-455v
Fixed in:

pip handles concatenated tar and ZIP files as ZIP files regardless of filename or whether a file is both a tar and ZIP file. This behavior could result in confusing installation behavior, such as inst


4. pip 24.0

CVE: GHSA-jp4c-xjxw-mgf9
Fixed in: 26.1

pip prior to version 26.1 would run self-update check functionality after installing wheel files which required importing well-known Python modules names. These module imports were intentionally defer

Powered by Codity.ai · Docs

@DhirenMhatre

Copy link
Copy Markdown
Author

@codity review

@codity-dm

codity-dm Bot commented May 19, 2026

Copy link
Copy Markdown

Policy Check Failed

✗ 3/3 policy checks failed:

• Need 2 more approval(s) (0/2) — comment LGTM or approve via review
• Missing ticket reference (expected: JIRA-, ENG-, #*)
• 5 code file(s) changed but no test files added


To merge this PR:

  1. Address the failed checks listed above
  2. Ensure branch protection requires the codity/policy-check status

Configure policies in your dashboard

@codity-dm

codity-dm Bot commented May 19, 2026

Copy link
Copy Markdown

PR Summary

What Changed

  • Extracted federated server proxy logic from CLI into a new FederatedServer struct in the p2p package for better separation of concerns.
  • Added conditional compilation support: P2P features compile with //go:build p2p tag, disabled builds get a stub that returns "not implemented".
  • Simplified core/cli/federated.go from ~120 lines to ~15 lines by delegating to the new p2p.NewFederatedServer() constructor.

Key Changes by Area

P2P Networking: New FederatedServer struct encapsulates server config and proxy implementation with build tag conditional compilation.

CLI: Federated command now delegates to p2p package, removing direct proxy handling logic.

Files Changed

File Changes Summary
core/cli/federated.go Reduced to ~15 lines, delegates server creation and start to p2p.NewFederatedServer()
core/p2p/federatedServer.go New file: FederatedServer struct with config fields (listen address, service ID, P2P token)
core/p2p/federation.go New file: extracted Start(), proxy(), handleConn() methods and copyStream helper from CLI
core/p2p/p2p.go Removed copyStream helper (moved to federation.go)
core/p2p/p2p_disabled.go Added stub FederatedServer.Start() returning "not implemented" for non-P2P builds

Review Focus Areas

  • Build tag correctness: verify //go:build p2p guards all P2P-specific code and disabled stub properly handles missing tag.
  • Error handling in FederatedServer.Start(): check propagation of listener and proxy errors to CLI.
  • copyStream relocation: confirm no other callers in p2p.go were missed.

Architecture

Design Decisions: The split follows a clear layering pattern. CLI handles command parsing and flag binding. p2p package owns networking implementation. Build tags control feature availability at compile time rather than runtime checks. This trades build complexity for zero runtime overhead in disabled builds.

Scalability & Extensibility: The FederatedServer struct is now testable without CLI dependencies. New proxy behaviors can be added to federation.go without touching CLI code. Out of scope: actual P2P protocol changes or service discovery.

Risks:

  • Intentional: Build tag drift. If federation.go and p2p_disabled.go diverge in exported API, compilation fails for one build configuration. This is acceptable and caught by CI.
  • Unintentional: copyStream move may have missed internal callers. Verify with grep or compiler.

Merge Status

NOT MERGEABLE — PR Score 34/100, below threshold (50)

  • [H2] 175 dependency vulnerabilities detected
  • [H4] PR quality score (34) is below merge floor (50)
  • [H5] 2 CRITICAL inline review findings need resolution
  • [H7] 1 HIGH-severity security finding

Comment thread core/p2p/federation.go
// open a TCP stream to one of the tunnels
// chosen randomly
// TODO: optimize this and track usage
tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional Critical

Selecting a random tunnel without checking for an empty list can panic, so return early when no online federated nodes are available.

Suggested fix
	if len(tunnelAddresses) == 0 {
		log.Error().Msg("No online federated nodes available")
		conn.Close()
		return
	}
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 106-106
Issue Type: functional-critical
Severity: critical

Issue Description:
Selecting a random tunnel without checking for an empty list can panic, so return early when no online federated nodes are available.

Current Code:
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/p2p/federation.go
Comment on lines +108 to +111
tunnelConn, err := net.Dial("tcp", tunnelAddr)
if err != nil {
log.Error().Err(err).Msg("Error connecting to tunnel")
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness High

The accepted client connection is left open on dial failure, so close it before returning.

Suggested fix
	tunnelConn, err := net.Dial("tcp", tunnelAddr)
	if err != nil {
		log.Error().Err(err).Msg("Error connecting to tunnel")
		conn.Close()
		return
	}
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 108-111
Issue Type: robustness-high
Severity: high

Issue Description:
The accepted client connection is left open on dial failure, so close it before returning.

Current Code:
	tunnelConn, err := net.Dial("tcp", tunnelAddr)
	if err != nil {
		log.Error().Err(err).Msg("Error connecting to tunnel")
		return
	}

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

@codity-dm

codity-dm Bot commented May 19, 2026

Copy link
Copy Markdown

Security Scan Summary

Metric Value
Vulnerabilities Critical: 0
Overall Risk Medium
Files Scanned 5

Consider addressing security findings before merging

Scan completed in 33.0s

View vulnerability details (2 items)

1. MATH_RANDOM_USED (CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)) HIGH

File: core/p2p/federation.go (line 16)
Category: Other

Do not use math/rand. Use crypto/rand instead.

Fix: Review and fix the security issue following OWASP guidelines.


2. SEC-001 (CWE-703) MEDIUM

File: core/p2p/federation.go (line 106)
Category: SAST

tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

The connection handler selects a random tunnel address using rand.IntN(len(tunnelAddresses)) without checking whether any nodes are available. If the list is empty (e.g., at startup or when no peers are online), this call will panic and terminate the process. An external client can trigger this condition by connecting when no tunnels are available, causing a denial of service.

Fix: Before calling rand.IntN, verify that tunnelAddresses is non-empty and handle the no-available-node case gracefully, e.g. by returning an error or closing the connection.


Security scan powered by Codity.ai

@codity-dm

codity-dm Bot commented May 19, 2026

Copy link
Copy Markdown

Dependency vulnerability scanning

Metric Value
Vulnerabilities Found 171
Scanner govulncheck
Top 10 Vulnerabilities (171 total found)

1. github.com/mudler/LocalAI 0+

CVE: GO-2024-3253
Fixed in: See OSV advisory

LocalAI Cross-site Scripting vulnerability in github.com/mudler/LocalAI


2. github.com/mudler/LocalAI 0+

CVE: GO-2025-3542
Fixed in: See OSV advisory

LocalAI Cross-Site Scripting (XSS) vulnerability in its search functionality in github.com/mudler/LocalAI


3. stdlib < 1.16.1

CVE: GO-2021-0067
Fixed in: See OSV advisory

Panic when opening archives in archive/zip


4. stdlib < 1.15.5

CVE: GO-2021-0069
Fixed in: See OSV advisory

Panic during division of very large numbers in math/big


5. stdlib < 1.14.7

CVE: GO-2021-0142
Fixed in: See OSV advisory

Unbounded read from invalid inputs in encoding/binary


6. stdlib < 1.3.2

CVE: GO-2021-0154
Fixed in: See OSV advisory

Man-in-the-middle attack with SessionTicketsDisabled in crypto/tls


7. stdlib < 1.4.3

CVE: GO-2021-0159
Fixed in: See OSV advisory

Request smuggling due to improper header parsing in net/http


8. stdlib < 1.5.3

CVE: GO-2021-0160
Fixed in: See OSV advisory

Incorrect calculation affecting RSA computations in math/big


9. stdlib < 1.6.1

CVE: GO-2021-0163
Fixed in: See OSV advisory

Privilege escalation on Windows via malicious DLL in syscall


10. stdlib < 1.7.4

CVE: GO-2021-0172
Fixed in: See OSV advisory

Denial of service when parsing large forms in mime/multipart


161 more vulnerabilities not shown. Update dependencies to fix these issues.

Powered by Codity.ai · Docs

@codity-dm

codity-dm Bot commented May 19, 2026

Copy link
Copy Markdown

Dependency vulnerability scanning

Metric Value
Vulnerabilities Found 4
Scanner pip-audit
View vulnerability details (4 items)

1. pip 24.0

CVE: GHSA-4xh5-x5gv-qwph
Fixed in: 25.3

When extracting a tar archive pip may not check symbolic links point into the extraction directory if the tarfile module doesn't implement PEP 706. Note that upgrading pip to a "fixed" version for thi


2. pip 24.0

CVE: GHSA-6vgw-5pg2-w6jp
Fixed in: 26.0

When pip is installing and extracting a maliciously crafted wheel archive, files may be extracted outside the installation directory. The path traversal is limited to prefixes of the installation dire


3. pip 24.0

CVE: GHSA-58qw-9mgm-455v
Fixed in:

pip handles concatenated tar and ZIP files as ZIP files regardless of filename or whether a file is both a tar and ZIP file. This behavior could result in confusing installation behavior, such as inst


4. pip 24.0

CVE: GHSA-jp4c-xjxw-mgf9
Fixed in: 26.1

pip prior to version 26.1 would run self-update check functionality after installing wheel files which required importing well-known Python modules names. These module imports were intentionally defer

Powered by Codity.ai · Docs

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

Policy Check Failed

✗ 3/3 policy checks failed:

• Need 2 more approval(s) (0/2) — comment LGTM or approve via review
• Missing ticket reference (expected: JIRA-, ENG-, #*)
• 5 code file(s) changed but no test files added


To merge this PR:

  1. Address the failed checks listed above
  2. Ensure branch protection requires the codity/policy-check status

Configure policies in your dashboard

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

PR Summary

What Changed

  • Extracted P2P proxy logic from CLI into a new FederatedServer struct in the p2p package for better separation of concerns.
  • Moved copyStream() helper to federation.go and removed the duplicate from p2p.go.
  • Added build tag support with stub Start() method for non-P2P builds.

Key Changes by Area

P2P Networking: New FederatedServer struct encapsulates server config and proxy handling. Full implementation in federation.go with Start(), proxy(), and handleConn() methods.

CLI: core/cli/federated.go simplified to just create and start the server. Removed unused imports.

Build System: Added stub Start() in p2p_disabled.go for builds without P2P support.

Files Changed

File Changes Summary
core/cli/federated.go Simplified to delegate to new FederatedServer; removed unused imports
core/p2p/federatedServer.go New file: FederatedServer struct definition with config fields
core/p2p/federation.go New file: full P2P implementation with Start(), proxy(), handleConn(), and copyStream()
core/p2p/p2p.go Removed duplicate copyStream() function
core/p2p/p2p_disabled.go Added stub Start() method for non-P2P builds

Review Focus Areas

  • Error handling in federation.go:handleConn() and proxy() methods.
  • Proper resource cleanup in copyStream() when connections close.
  • Build tag coverage: verify p2p_disabled.go stub matches FederatedServer interface.

Architecture

Design Decisions: Moved P2P logic out of CLI to improve testability and follow package boundaries. The FederatedServer struct uses plain fields (not interfaces) for config. This is acceptable for internal use but limits mocking in tests.

Risks: copyStream() uses io.Copy without timeouts. This is intentional for raw stream proxying but may hang on stale connections. Consider if context cancellation is sufficient.

Merge Status

NOT MERGEABLE — PR Score 34/100, below threshold (50)

  • [H2] 194 dependency vulnerabilities detected
  • [H4] PR quality score (34) is below merge floor (50)
  • [H5] 2 CRITICAL inline review findings need resolution
  • [H7] 1 HIGH-severity security finding

Comment thread core/p2p/federation.go
// open a TCP stream to one of the tunnels
// chosen randomly
// TODO: optimize this and track usage
tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional Critical

Selecting a random tunnel without checking for an empty slice will panic, so return early when no online nodes are available.

Suggested fix
	if len(tunnelAddresses) == 0 {
		log.Error().Msg("No online federated nodes available")
		conn.Close()
		return
	}
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 106-106
Issue Type: functional-critical
Severity: critical

Issue Description:
Selecting a random tunnel without checking for an empty slice will panic, so return early when no online nodes are available.

Current Code:
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/p2p/federation.go
Comment on lines +108 to +111
tunnelConn, err := net.Dial("tcp", tunnelAddr)
if err != nil {
log.Error().Err(err).Msg("Error connecting to tunnel")
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness High

The accepted client connection is leaked when net.Dial fails, so close conn before returning on this error path.

Suggested fix
	tunnelConn, err := net.Dial("tcp", tunnelAddr)
	if err != nil {
		log.Error().Err(err).Msg("Error connecting to tunnel")
		conn.Close()
		return
	}
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 108-111
Issue Type: robustness-high
Severity: high

Issue Description:
The accepted client connection is leaked when net.Dial fails, so close conn before returning on this error path.

Current Code:
	tunnelConn, err := net.Dial("tcp", tunnelAddr)
	if err != nil {
		log.Error().Err(err).Msg("Error connecting to tunnel")
		return
	}

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

Security Scan Summary

Metric Value
Vulnerabilities Critical: 0
Overall Risk Medium
Files Scanned 5

Consider addressing security findings before merging

Scan completed in 31.1s

View vulnerability details (2 items)

1. MATH_RANDOM_USED (CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)) HIGH

File: core/p2p/federation.go (line 16)
Category: Other

Do not use math/rand. Use crypto/rand instead.

Fix: Review and fix the security issue following OWASP guidelines.


2. SEC-DO-001 (CWE-400) MEDIUM

File: core/p2p/federation.go (line 106)
Category: SAST

tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

The handler selects a random tunnel address without checking whether any peers are available. When no nodes are online, len(tunnelAddresses) is zero and rand.IntN(0) will panic, crashing the server upon an incoming connection. This allows a trivial denial-of-service by connecting when no tunnels are available.

Fix: Before calling rand.IntN, verify that tunnelAddresses is non-empty and handle the case where no peers are available by rejecting the connection or waiting for a node to come online.


Security scan powered by Codity.ai

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

Dependency vulnerability scanning

Metric Value
Vulnerabilities Found 171
Scanner govulncheck
Top 10 Vulnerabilities (171 total found)

1. github.com/mudler/LocalAI 0+

CVE: GO-2024-3253
Fixed in: See OSV advisory

LocalAI Cross-site Scripting vulnerability in github.com/mudler/LocalAI


2. github.com/mudler/LocalAI 0+

CVE: GO-2025-3542
Fixed in: See OSV advisory

LocalAI Cross-Site Scripting (XSS) vulnerability in its search functionality in github.com/mudler/LocalAI


3. stdlib < 1.16.1

CVE: GO-2021-0067
Fixed in: See OSV advisory

Panic when opening archives in archive/zip


4. stdlib < 1.15.5

CVE: GO-2021-0069
Fixed in: See OSV advisory

Panic during division of very large numbers in math/big


5. stdlib < 1.14.7

CVE: GO-2021-0142
Fixed in: See OSV advisory

Unbounded read from invalid inputs in encoding/binary


6. stdlib < 1.3.2

CVE: GO-2021-0154
Fixed in: See OSV advisory

Man-in-the-middle attack with SessionTicketsDisabled in crypto/tls


7. stdlib < 1.4.3

CVE: GO-2021-0159
Fixed in: See OSV advisory

Request smuggling due to improper header parsing in net/http


8. stdlib < 1.5.3

CVE: GO-2021-0160
Fixed in: See OSV advisory

Incorrect calculation affecting RSA computations in math/big


9. stdlib < 1.6.1

CVE: GO-2021-0163
Fixed in: See OSV advisory

Privilege escalation on Windows via malicious DLL in syscall


10. stdlib < 1.7.4

CVE: GO-2021-0172
Fixed in: See OSV advisory

Denial of service when parsing large forms in mime/multipart


161 more vulnerabilities not shown. Update dependencies to fix these issues.

Powered by Codity.ai · Docs

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

Dependency vulnerability scanning

Metric Value
Vulnerabilities Found 23
Scanner pip-audit
Top 10 Vulnerabilities (23 total found)

1. pip 24.0

CVE: GHSA-4xh5-x5gv-qwph
Fixed in: 25.3

When extracting a tar archive pip may not check symbolic links point into the extraction directory if the tarfile module doesn't implement PEP 706. Note that upgrading pip to a "fixed" version for thi


2. pip 24.0

CVE: GHSA-6vgw-5pg2-w6jp
Fixed in: 26.0

When pip is installing and extracting a maliciously crafted wheel archive, files may be extracted outside the installation directory. The path traversal is limited to prefixes of the installation dire


3. pip 24.0

CVE: GHSA-58qw-9mgm-455v
Fixed in: 26.1

pip handles concatenated tar and ZIP files as ZIP files regardless of filename or whether a file is both a tar and ZIP file. This behavior could result in confusing installation behavior, such as inst


4. pip 24.0

CVE: GHSA-jp4c-xjxw-mgf9
Fixed in: 26.1

pip prior to version 26.1 would run self-update check functionality after installing wheel files which required importing well-known Python modules names. These module imports were intentionally defer


5. torch 2.12.0

CVE: PYSEC-2025-210
Fixed in:

An issue was discovered in PyTorch v2.5 and v2.7.1. Omission of profiler.stop() can cause torch.profiler.profile (PythonTracer) to crash or hang during finalization, leading to a Denial of Service (Do


6. torch 2.12.0

CVE: PYSEC-2025-194
Fixed in:

A vulnerability classified as critical has been found in PyTorch 2.6.0. This affects the function torch.jit.script. The manipulation leads to memory corruption. It is possible to launch the attack on


7. torch 2.12.0

CVE: PYSEC-2025-196
Fixed in:

A vulnerability classified as problematic has been found in PyTorch 2.6.0. Affected is the function torch.jit.jit_module_from_flatbuffer. The manipulation leads to memory corruption. Local access is r


8. torch 2.12.0

CVE: PYSEC-2025-195
Fixed in:

A vulnerability classified as critical was found in PyTorch 2.6.0. This vulnerability affects the function torch.lstm_cell. The manipulation leads to memory corruption. The attack needs to be approach


9. torch 2.12.0

CVE: PYSEC-2025-193
Fixed in:

A vulnerability was found in PyTorch 2.6.0. It has been rated as critical. Affected by this issue is the function torch.nn.utils.rnn.unpack_sequence. The manipulation leads to memory corruption. Attac


10. torch 2.12.0

CVE: PYSEC-2025-192
Fixed in:

A vulnerability was found in PyTorch 2.6.0. It has been declared as critical. Affected by this vulnerability is the function torch.nn.utils.rnn.pad_packed_sequence. The manipulation leads to memory co


13 more vulnerabilities not shown. Update dependencies to fix these issues.

Powered by Codity.ai · Docs

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

License Compliance Scan

Metric Value
Packages Scanned 469
High Risk (Strong Copyleft) 0
Medium Risk (Weak Copyleft) 8
Low Risk (Permissive) 408
Unknown License 53

Weak copyleft licenses found - verify compatibility

Some packages have unknown licenses - manual review required

Medium Risk Licenses - 8 packages

MPL-2.0 (6 packages):

  • github.com/hashicorp/go-multierror 1.1.1
  • github.com/hashicorp/golang-lru 1.0.2
  • github.com/hashicorp/golang-lru/v2 2.0.7
  • github.com/hashicorp/errwrap 1.1.0
  • github.com/libp2p/go-yamux/v4 4.0.1
  • github.com/shoenig/go-m1cpu 0.1.6

Mozilla Public License 2.0 (MPL 2.0) (2 packages):

  • TTS 0.22.0
  • certifi 2024.7.4
Unknown Licenses - 53 packages
  • eng_to_ipa 0.0.2
  • github.com/marten-seemann/tcp 0.0.0-20210406111302-dfbc87cc63fd
  • github.com/miekg/dns 1.1.61
  • github.com/mikioh/tcpopt 0.0.0-20190314235656-172688c1accc
  • github.com/mikioh/tcpinfo 0.0.0-20190314235526-30a79bb1804b
  • github.com/minio/sha256-simd 1.0.1
  • github.com/moby/sys/sequential 0.5.0
  • github.com/moby/term 0.5.0
  • github.com/mudler/water 0.0.0-20221010214108-8c7313014ce0
  • github.com/multiformats/go-base32 0.1.0
  • github.com/olekukonko/tablewriter 0.0.5
  • github.com/nwaples/rardecode 1.1.0
  • github.com/opencontainers/image-spec 1.1.0
  • github.com/opencontainers/go-digest 1.0.0
  • github.com/opencontainers/runc 1.1.12
  • github.com/opencontainers/runtime-spec 1.2.0
  • github.com/opentracing/opentracing-go 1.2.0
  • github.com/pbnjay/memory 0.0.0-20210728143218-7b4eea64cf58
  • github.com/peterbourgon/diskv 2.0.1+incompatible
  • github.com/pierrec/lz4/v4 4.1.2

...and 33 more

Powered by Codity.ai · Docs

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

Code Quality Report — test-org-codity/LocalAI · PR #3

Scanned: 2026-05-21 10:28 UTC | Score: 57/100 | Provider: github

Executive Summary

Severity Count
Critical 0
High 2
Medium 2
Low 2
Top Findings

[CQ-LLM-001] core/p2p/federation.go:1 (Complexity · HIGH)

Issue: The 'proxy' function has deep nesting due to the for loop and select statement.
Suggestion: Consider refactoring the 'proxy' function to reduce nesting and improve readability.

for {
	select {
	case <-ctx.Done():
		return errors.New("context canceled")
	default:
		log.Debug().Msg("New for connection")
		// Listen for an incoming connection.
		conn, err := l.Accept()
		if err != nil {
			fmt.Println("Error accepting: ", err.Error())
			continue
		}
		
		// Handle connections in a new goroutine, forwarding to the p2p service
		go handleConn(conn)
	}
}

[CQ-LLM-003] core/p2p/federation.go:1 (Error_Handling · HIGH)

Issue: The 'Start' method of 'FederatedServer' does not handle potential errors from 'NewNode' and 'Start'.
Suggestion: Ensure that all errors are properly handled and logged to avoid silent failures.

n, err := NewNode(fs.p2ptoken)
if err != nil {
	return fmt.Errorf("creating a new node: %w", err)
}

[CQ-LLM-002] core/p2p/federation.go:1 (Duplication · MEDIUM)

Issue: The 'copyStream' function is duplicated in both 'federation.go' and 'p2p.go'.
Suggestion: Remove the duplicate 'copyStream' function from 'p2p.go' and use the one in 'federation.go'.

func copyStream(closer chan struct{}, dst io.Writer, src io.Reader) {
	defer func() { closer <- struct{}{} }() // connection is closed, send signal to stop proxy
	io.Copy(dst, src)
}

[CQ-LLM-004] core/p2p/federation.go:1 (Documentation · MEDIUM)

Issue: Missing documentation for public methods in 'FederatedServer'.
Suggestion: Add docstrings to the 'Start' and 'proxy' methods to explain their purpose and usage.

func (fs *FederatedServer) Start(ctx context.Context) error {
	// TODO: Add documentation
}

[CQ-LLM-005] core/p2p/federation.go:1 (Maintainability · LOW)

Issue: The use of magic numbers (10) in the 'Announce' method could be improved.
Suggestion: Define a constant for the timeout duration instead of using a magic number.

10*time.Second

[CQ-008] core/p2p/federation.go:56 (Maintainability · LOW)

Issue: Magic number 10 in code
Suggestion: Extract to a named constant

10*time.Second,

Per-File Breakdown

File Critical High Medium Low Total
core/p2p/federation.go 0 2 2 2 6

Recommendations

  1. Resolve High severity issues, especially error handling gaps and performance bottlenecks.
  • Run automated tests after applying fixes to verify no regressions.

@DhirenMhatre

Copy link
Copy Markdown
Author

@codity review

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

Policy Check Failed

✗ 3/3 policy checks failed:

• Need 2 more approval(s) (0/2) — comment LGTM or approve via review
• Missing ticket reference (expected: JIRA-, ENG-, #*)
• 5 code file(s) changed but no test files added


To merge this PR:

  1. Address the failed checks listed above
  2. Ensure branch protection requires the codity/policy-check status

Configure policies in your dashboard

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

PR Summary

What Changed

  • Extracted federated server proxy logic from CLI into a reusable FederatedServer type in the p2p package.
  • Simplified core/cli/federated.go to a thin wrapper that constructs and starts the server.
  • Added build tag support for non-P2P builds via stub in p2p_disabled.go.

Key Changes by Area

P2P Core: New FederatedServer struct encapsulates server config and proxy lifecycle (Start, proxy, handleConn methods).

CLI: federated.go reduced to ~10 lines using NewFederatedServer() constructor.

Build System: p2p_disabled.go now includes FederatedServer.Start() stub for builds without P2P support.

Files Changed

File Changes Summary
core/cli/federated.go Simplified to thin wrapper using NewFederatedServer()
core/p2p/federatedServer.go New struct definition for server configuration
core/p2p/federation.go New file with full proxy implementation (Start, proxy, handleConn, copyStream)
core/p2p/p2p.go Removed duplicate copyStream() function
core/p2p/p2p_disabled.go Added FederatedServer.Start() stub for non-P2P builds

Review Focus Areas

  • Tunnel selection logic in handleConn() for random peer selection behavior.
  • Error handling during P2P node initialization in Start().
  • Build tag compatibility: verify p2p_disabled.go stub matches FederatedServer interface.

Architecture

Design Decisions: The split between federatedServer.go (config) and federation.go (implementation) appears intentional to separate data from behavior. Moving copyStream() to federation.go centralizes stream utilities in the P2P package.

Scalability & Extensibility: FederatedServer is now reusable outside CLI context (as hinted by run.go integration in context). This enables programmatic server creation without CLI coupling.

Risks: Random tunnel selection in handleConn() is a deliberate simplification. No connection retry or health checking on peers. This is acceptable for initial implementation but limits reliability under peer churn.

Merge Status

NOT MERGEABLE — PR Score 32/100, below threshold (50)

  • [H2] 194 dependency vulnerabilities detected
  • [H4] PR quality score (32) is below merge floor (50)
  • [H5] 2 CRITICAL inline review findings need resolution
  • [H7] 1 HIGH-severity security finding

Comment thread core/p2p/federation.go
// open a TCP stream to one of the tunnels
// chosen randomly
// TODO: optimize this and track usage
tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional Critical

Selecting a random tunnel from an empty slice panics, so return early when no online federated nodes are available.

Suggested fix
	if len(tunnelAddresses) == 0 {
		log.Error().Msg("No online federated nodes available")
		conn.Close()
		return
	}
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 106-106
Issue Type: functional-critical
Severity: critical

Issue Description:
Selecting a random tunnel from an empty slice panics, so return early when no online federated nodes are available.

Current Code:
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/cli/federated.go
func copyStream(closer chan struct{}, dst io.Writer, src io.Reader) {
defer func() { closer <- struct{}{} }() // connection is closed, send signal to stop proxy
io.Copy(dst, src)
return fs.Start(context.Background())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional High

This ignores the CLI context and starts the server with a detached background context, so shutdown and cancellation will not propagate; pass the provided context instead.

Suggested change
return fs.Start(context.Background())
return fs.Start(ctx)
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/cli/federated.go
Lines: 18-18
Issue Type: functional-high
Severity: high

Issue Description:
This ignores the CLI context and starts the server with a detached background context, so shutdown and cancellation will not propagate; pass the provided context instead.

Current Code:
	return fs.Start(context.Background())

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/p2p/federation.go
Comment on lines +108 to +111
tunnelConn, err := net.Dial("tcp", tunnelAddr)
if err != nil {
log.Error().Err(err).Msg("Error connecting to tunnel")
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness High

The accepted client connection is leaked on dial failure, so close conn before returning.

Suggested fix
	tunnelConn, err := net.Dial("tcp", tunnelAddr)
	if err != nil {
		log.Error().Err(err).Msg("Error connecting to tunnel")
		conn.Close()
		return
	}
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 108-111
Issue Type: robustness-high
Severity: high

Issue Description:
The accepted client connection is leaked on dial failure, so close conn before returning.

Current Code:
	tunnelConn, err := net.Dial("tcp", tunnelAddr)
	if err != nil {
		log.Error().Err(err).Msg("Error connecting to tunnel")
		return
	}

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

Security Scan Summary

Metric Value
Vulnerabilities Critical: 0
Overall Risk Medium
Files Scanned 5

Consider addressing security findings before merging

Scan completed in 23.4s

View vulnerability details (1 items)

1. MATH_RANDOM_USED (CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)) HIGH

File: core/p2p/federation.go (line 16)
Category: Other

Do not use math/rand. Use crypto/rand instead.

Fix: Review and fix the security issue following OWASP guidelines.


Security scan powered by Codity.ai

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

Dependency vulnerability scanning

Metric Value
Vulnerabilities Found 171
Scanner govulncheck
Top 10 Vulnerabilities (171 total found)

1. stdlib < 1.16.1

CVE: GO-2021-0067
Fixed in: See OSV advisory

Panic when opening archives in archive/zip


2. stdlib < 1.15.5

CVE: GO-2021-0069
Fixed in: See OSV advisory

Panic during division of very large numbers in math/big


3. stdlib < 1.14.7

CVE: GO-2021-0142
Fixed in: See OSV advisory

Unbounded read from invalid inputs in encoding/binary


4. stdlib < 1.3.2

CVE: GO-2021-0154
Fixed in: See OSV advisory

Man-in-the-middle attack with SessionTicketsDisabled in crypto/tls


5. stdlib < 1.4.3

CVE: GO-2021-0159
Fixed in: See OSV advisory

Request smuggling due to improper header parsing in net/http


6. stdlib < 1.5.3

CVE: GO-2021-0160
Fixed in: See OSV advisory

Incorrect calculation affecting RSA computations in math/big


7. stdlib < 1.6.1

CVE: GO-2021-0163
Fixed in: See OSV advisory

Privilege escalation on Windows via malicious DLL in syscall


8. stdlib < 1.7.4

CVE: GO-2021-0172
Fixed in: See OSV advisory

Denial of service when parsing large forms in mime/multipart


9. stdlib < 1.9.1

CVE: GO-2021-0178
Fixed in: See OSV advisory

Cleartext transmission of credentials in net/smtp


10. stdlib < 1.14.5

CVE: GO-2021-0223
Fixed in: See OSV advisory

Certificate verification error on Windows in crypto/x509


161 more vulnerabilities not shown. Update dependencies to fix these issues.

Powered by Codity.ai · Docs

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

Dependency vulnerability scanning

Metric Value
Vulnerabilities Found 23
Scanner pip-audit
Top 10 Vulnerabilities (23 total found)

1. pip 24.0

CVE: GHSA-4xh5-x5gv-qwph
Fixed in: 25.3

When extracting a tar archive pip may not check symbolic links point into the extraction directory if the tarfile module doesn't implement PEP 706. Note that upgrading pip to a "fixed" version for thi


2. pip 24.0

CVE: GHSA-6vgw-5pg2-w6jp
Fixed in: 26.0

When pip is installing and extracting a maliciously crafted wheel archive, files may be extracted outside the installation directory. The path traversal is limited to prefixes of the installation dire


3. pip 24.0

CVE: GHSA-58qw-9mgm-455v
Fixed in: 26.1

pip handles concatenated tar and ZIP files as ZIP files regardless of filename or whether a file is both a tar and ZIP file. This behavior could result in confusing installation behavior, such as inst


4. pip 24.0

CVE: GHSA-jp4c-xjxw-mgf9
Fixed in: 26.1

pip prior to version 26.1 would run self-update check functionality after installing wheel files which required importing well-known Python modules names. These module imports were intentionally defer


5. torch 2.12.0

CVE: PYSEC-2025-210
Fixed in:

An issue was discovered in PyTorch v2.5 and v2.7.1. Omission of profiler.stop() can cause torch.profiler.profile (PythonTracer) to crash or hang during finalization, leading to a Denial of Service (Do


6. torch 2.12.0

CVE: PYSEC-2025-194
Fixed in:

A vulnerability classified as critical has been found in PyTorch 2.6.0. This affects the function torch.jit.script. The manipulation leads to memory corruption. It is possible to launch the attack on


7. torch 2.12.0

CVE: PYSEC-2025-196
Fixed in:

A vulnerability classified as problematic has been found in PyTorch 2.6.0. Affected is the function torch.jit.jit_module_from_flatbuffer. The manipulation leads to memory corruption. Local access is r


8. torch 2.12.0

CVE: PYSEC-2025-195
Fixed in:

A vulnerability classified as critical was found in PyTorch 2.6.0. This vulnerability affects the function torch.lstm_cell. The manipulation leads to memory corruption. The attack needs to be approach


9. torch 2.12.0

CVE: PYSEC-2025-193
Fixed in:

A vulnerability was found in PyTorch 2.6.0. It has been rated as critical. Affected by this issue is the function torch.nn.utils.rnn.unpack_sequence. The manipulation leads to memory corruption. Attac


10. torch 2.12.0

CVE: PYSEC-2025-192
Fixed in:

A vulnerability was found in PyTorch 2.6.0. It has been declared as critical. Affected by this vulnerability is the function torch.nn.utils.rnn.pad_packed_sequence. The manipulation leads to memory co


13 more vulnerabilities not shown. Update dependencies to fix these issues.

Powered by Codity.ai · Docs

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

License Compliance Scan

Metric Value
Packages Scanned 469
High Risk (Strong Copyleft) 0
Medium Risk (Weak Copyleft) 8
Low Risk (Permissive) 413
Unknown License 48

Weak copyleft licenses found - verify compatibility

Some packages have unknown licenses - manual review required

Medium Risk Licenses - 8 packages

MPL-2.0 (6 packages):

  • github.com/hashicorp/go-multierror 1.1.1
  • github.com/hashicorp/errwrap 1.1.0
  • github.com/hashicorp/golang-lru/v2 2.0.7
  • github.com/hashicorp/golang-lru 1.0.2
  • github.com/libp2p/go-yamux/v4 4.0.1
  • github.com/shoenig/go-m1cpu 0.1.6

Mozilla Public License 2.0 (MPL 2.0) (2 packages):

  • TTS 0.22.0
  • certifi 2024.7.4
Unknown Licenses - 48 packages
  • eng_to_ipa 0.0.2
  • github.com/go-openapi/swag 0.23.0
  • github.com/go-openapi/jsonreference 0.21.0
  • github.com/go-logr/stdr 1.2.2
  • github.com/go-openapi/jsonpointer 0.21.0
  • github.com/go-openapi/spec 0.21.0
  • github.com/golang/groupcache 0.0.0-20210331224755-41bb18bfe9da
  • github.com/gogo/protobuf 1.3.2
  • github.com/google/btree 1.1.2
  • github.com/golang/snappy 0.0.4
  • github.com/google/go-cmp 0.6.0
  • github.com/google/pprof 0.0.0-20240424215950-a892ee059fd6
  • github.com/gorilla/css 1.0.1
  • github.com/google/gopacket 1.1.19
  • github.com/google/shlex 0.0.0-20191202100458-e7afc7fbc510
  • github.com/gorilla/websocket 1.5.3
  • github.com/imdario/mergo 0.3.16
  • github.com/huin/goupnp 1.3.0
  • github.com/jaypipes/pcidb 1.0.0
  • github.com/klauspost/compress 1.17.9

...and 28 more

Powered by Codity.ai · Docs

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

Code Quality Report — test-org-codity/LocalAI · PR #3

Scanned: 2026-05-21 10:44 UTC | Score: 54/100 | Provider: github

Executive Summary

Severity Count
Critical 0
High 2
Medium 3
Low 2
Top Findings

[CQ-LLM-001] core/p2p/federation.go:1 (Complexity · HIGH)

Issue: The 'proxy' function has deep nesting due to the for loop and select statement.
Suggestion: Consider refactoring the 'proxy' function to reduce nesting and improve readability.

for {
	select {
	case <-ctx.Done():
		return errors.New("context canceled")
	default:
		log.Debug().Msg("New for connection")
		// Listen for an incoming connection.
		conn, err := l.Accept()
		if err != nil {
			fmt.Println("Error accepting: ", err.Error())
			continue
		}
		// Handle connections in a new goroutine, forwarding to the p2p service
		go handleConn(conn)
	}
}

[CQ-LLM-003] core/p2p/federation.go:1 (Error_Handling · HIGH)

Issue: The 'Start' method of 'FederatedServer' does not handle potential errors from 'NewNode' and 'Start'.
Suggestion: Ensure that all errors are properly handled and logged to avoid silent failures.

n, err := NewNode(fs.p2ptoken)
if err != nil {
	return fmt.Errorf("creating a new node: %w", err)
}

[CQ-LLM-002] core/p2p/federation.go:1 (Duplication · MEDIUM)

Issue: The 'copyStream' function is duplicated in both 'federation.go' and 'p2p.go'.
Suggestion: Remove the duplicate 'copyStream' function from one of the files and ensure it is used from a single location.

func copyStream(closer chan struct{}, dst io.Writer, src io.Reader) {
	defer func() { closer <- struct{}{} }() // connection is closed, send signal to stop proxy
	io.Copy(dst, src)
}

[CQ-LLM-004] core/p2p/federation.go:1 (Performance · MEDIUM)

Issue: The 'proxy' function may lead to performance issues due to the blocking nature of 'l.Accept()' in a loop.
Suggestion: Consider using a worker pool or limiting the number of concurrent connections to improve performance.

conn, err := l.Accept()

[CQ-LLM-006] core/p2p/federation.go:1 (Maintainability · MEDIUM)

Issue: The use of magic strings like 'context canceled' can reduce maintainability.
Suggestion: Define constants for error messages to improve maintainability and avoid duplication.

return errors.New("context canceled")

[CQ-LLM-005] core/p2p/federation.go:1 (Documentation · LOW)

Issue: Missing documentation for public methods in 'FederatedServer'.
Suggestion: Add docstrings to the 'Start' and 'proxy' methods to describe their functionality and parameters.

func (fs *FederatedServer) Start(ctx context.Context) error {

[CQ-008] core/p2p/federation.go:56 (Maintainability · LOW)

Issue: Magic number 10 in code
Suggestion: Extract to a named constant

10*time.Second,

Per-File Breakdown

File Critical High Medium Low Total
core/p2p/federation.go 0 2 3 2 7

Recommendations

  1. Resolve High severity issues, especially error handling gaps and performance bottlenecks.
  • Run automated tests after applying fixes to verify no regressions.

@DhirenMhatre

Copy link
Copy Markdown
Author

@codity review

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

Policy Check Failed

✗ 3/3 policy checks failed:

• Need 2 more approval(s) (0/2) — comment LGTM or approve via review
• Missing ticket reference (expected: JIRA-, ENG-, #*)
• 5 code file(s) changed but no test files added


To merge this PR:

  1. Address the failed checks listed above
  2. Ensure branch protection requires the codity/policy-check status

Configure policies in your dashboard

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

PR Summary

What Changed

  • Extracted FederatedServer from CLI into a dedicated P2P package with proper build tag support.
  • Simplified core/cli/federated.go from ~120 lines to ~20 lines by delegating to the new P2P package.
  • Moved copyStream() helper to live with its only consumer in the federation code.

Key Changes by Area

P2P Package: Added FederatedServer struct with Start(), proxy(), and handleConn() methods in federation.go (P2P builds) and stub in p2p_disabled.go (non-P2P builds).

CLI: Reduced federated.go to thin wrapper that constructs and starts the server via p2p.NewFederatedServer().

Files Changed

File Changes Summary
core/cli/federated.go Reduced to ~20 lines, delegates to p2p.NewFederatedServer()
core/p2p/federatedServer.go New file: FederatedServer struct definition and constructor
core/p2p/federation.go New file: P2P-enabled implementation with Start(), proxy(), handleConn()
core/p2p/p2p.go Removed copyStream() helper (moved to federation.go)
core/p2p/p2p_disabled.go New file: Stub implementation for non-P2P builds

Review Focus Areas

  • Build tag consistency: Verify //go:build p2p matches existing patterns across the codebase.
  • Error handling in federation.go:handleConn() and proxy() methods during connection failures.
  • Ensure no P2P imports leak back into CLI package after this refactor.

Architecture

Design Decisions: The split follows existing build tag patterns (p2p_disabled.go mirrors p2p.go structure). The copyStream() move is intentional colocation with its only caller.

Scalability & Extensibility: Out of scope. This is a pure refactor with no behavior change.

Risks:

  • Intentional: p2p_disabled.go provides no-op stubs, callers must handle nil/empty behavior appropriately.
  • Unintentional: Verify non-P2P builds still compile and CLI falls gracefully when P2P is disabled.

Merge Status

NOT MERGEABLE — PR Score 33/100, below threshold (50)

  • [H2] 194 dependency vulnerabilities detected
  • [H4] PR quality score (33) is below merge floor (50)
  • [H5] 3 CRITICAL inline review findings need resolution
  • [H7] 1 HIGH-severity security finding

Comment thread core/cli/federated.go
}

func (f *FederatedCLI) Run(ctx *cliContext.Context) error {
fs := p2p.NewFederatedServer(f.Address, p2p.FederatedID, f.Peer2PeerToken)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional Critical

In a non-p2p build, running the federated CLI now always fails with "not implemented" because this caller was switched to FederatedServer.Start while the new implementation exists only in the p2p-only file; trigger: build without the p2p tag and execute the federated command.

Either move the real FederatedServer.Start implementation into an untagged file, add the same build tag to the CLI command so it is unavailable without p2p, or preserve the previous non-tagged implementation path.

Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/cli/federated.go
Lines: 16-16
Issue Type: functional-critical
Severity: critical

Issue Description:
In a non-p2p build, running the federated CLI now always fails with "not implemented" because this caller was switched to FederatedServer.Start while the new implementation exists only in the p2p-only file; trigger: build without the `p2p` tag and execute the federated command.

Current Code:
fs := p2p.NewFederatedServer(f.Address, p2p.FederatedID, f.Peer2PeerToken)

return fs.Start(context.Background())

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/p2p/federation.go
// open a TCP stream to one of the tunnels
// chosen randomly
// TODO: optimize this and track usage
tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional Critical

Selecting a tunnel with rand.IntN(len(tunnelAddresses)) panics when no online federated nodes are available, so guard the empty slice and close the client connection cleanly.

Suggested fix
	if len(tunnelAddresses) == 0 {
		log.Error().Msg("No online federated nodes available")
		conn.Close()
		return
	}
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 106-106
Issue Type: functional-critical
Severity: critical

Issue Description:
Selecting a tunnel with rand.IntN(len(tunnelAddresses)) panics when no online federated nodes are available, so guard the empty slice and close the client connection cleanly.

Current Code:
	tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/p2p/federation.go
Comment on lines +108 to +111
tunnelConn, err := net.Dial("tcp", tunnelAddr)
if err != nil {
log.Error().Err(err).Msg("Error connecting to tunnel")
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness High

The accepted client connection is leaked on tunnel dial failure, so close conn before returning from the error path.

Suggested fix
	tunnelConn, err := net.Dial("tcp", tunnelAddr)
	if err != nil {
		log.Error().Err(err).Msg("Error connecting to tunnel")
		conn.Close()
		return
	}
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 108-111
Issue Type: robustness-high
Severity: high

Issue Description:
The accepted client connection is leaked on tunnel dial failure, so close conn before returning from the error path.

Current Code:
	tunnelConn, err := net.Dial("tcp", tunnelAddr)
	if err != nil {
		log.Error().Err(err).Msg("Error connecting to tunnel")
		return
	}

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/p2p/federation.go
}

// Handle connections in a new goroutine, forwarding to the p2p service
go handleConn(conn)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance High

Spawning an unbounded goroutine for every accepted connection allows trivial resource exhaustion, so enforce a concurrency limit or backpressure before launching handleConn.

Suggested fix
			select {
			case sem <- struct{}{}:
				go func() {
					defer func() { <-sem }()
					handleConn(conn)
				}()
			default:
				log.Error().Msg("Too many concurrent connections")
				conn.Close()
			}
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert go developer with deep knowledge of security, performance, and best practices.

### Context

File: core/p2p/federation.go
Lines: 87-87
Issue Type: performance-high
Severity: high

Issue Description:
Spawning an unbounded goroutine for every accepted connection allows trivial resource exhaustion, so enforce a concurrency limit or backpressure before launching handleConn.

Current Code:
			go handleConn(conn)

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow go best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

Security Scan Summary

Metric Value
Vulnerabilities Critical: 0
Overall Risk Medium
Files Scanned 5

Consider addressing security findings before merging

Scan completed in 21.9s

View vulnerability details (1 items)

1. MATH_RANDOM_USED (CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)) HIGH

File: core/p2p/federation.go (line 16)
Category: Other

Do not use math/rand. Use crypto/rand instead.

Fix: Review and fix the security issue following OWASP guidelines.


Security scan powered by Codity.ai

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

Dependency vulnerability scanning

Metric Value
Vulnerabilities Found 171
Scanner govulncheck
Top 10 Vulnerabilities (171 total found)

1. stdlib < 1.16.1

CVE: GO-2021-0067
Fixed in: See OSV advisory

Panic when opening archives in archive/zip


2. stdlib < 1.15.5

CVE: GO-2021-0069
Fixed in: See OSV advisory

Panic during division of very large numbers in math/big


3. stdlib < 1.14.7

CVE: GO-2021-0142
Fixed in: See OSV advisory

Unbounded read from invalid inputs in encoding/binary


4. stdlib < 1.3.2

CVE: GO-2021-0154
Fixed in: See OSV advisory

Man-in-the-middle attack with SessionTicketsDisabled in crypto/tls


5. stdlib < 1.4.3

CVE: GO-2021-0159
Fixed in: See OSV advisory

Request smuggling due to improper header parsing in net/http


6. stdlib < 1.5.3

CVE: GO-2021-0160
Fixed in: See OSV advisory

Incorrect calculation affecting RSA computations in math/big


7. stdlib < 1.6.1

CVE: GO-2021-0163
Fixed in: See OSV advisory

Privilege escalation on Windows via malicious DLL in syscall


8. stdlib < 1.7.4

CVE: GO-2021-0172
Fixed in: See OSV advisory

Denial of service when parsing large forms in mime/multipart


9. stdlib < 1.9.1

CVE: GO-2021-0178
Fixed in: See OSV advisory

Cleartext transmission of credentials in net/smtp


10. stdlib < 1.14.5

CVE: GO-2021-0223
Fixed in: See OSV advisory

Certificate verification error on Windows in crypto/x509


161 more vulnerabilities not shown. Update dependencies to fix these issues.

Powered by Codity.ai · Docs

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

Dependency vulnerability scanning

Metric Value
Vulnerabilities Found 23
Scanner pip-audit
Top 10 Vulnerabilities (23 total found)

1. pip 24.0

CVE: GHSA-4xh5-x5gv-qwph
Fixed in: 25.3

When extracting a tar archive pip may not check symbolic links point into the extraction directory if the tarfile module doesn't implement PEP 706. Note that upgrading pip to a "fixed" version for thi


2. pip 24.0

CVE: GHSA-6vgw-5pg2-w6jp
Fixed in: 26.0

When pip is installing and extracting a maliciously crafted wheel archive, files may be extracted outside the installation directory. The path traversal is limited to prefixes of the installation dire


3. pip 24.0

CVE: GHSA-58qw-9mgm-455v
Fixed in: 26.1

pip handles concatenated tar and ZIP files as ZIP files regardless of filename or whether a file is both a tar and ZIP file. This behavior could result in confusing installation behavior, such as inst


4. pip 24.0

CVE: GHSA-jp4c-xjxw-mgf9
Fixed in: 26.1

pip prior to version 26.1 would run self-update check functionality after installing wheel files which required importing well-known Python modules names. These module imports were intentionally defer


5. torch 2.12.0

CVE: PYSEC-2025-210
Fixed in:

An issue was discovered in PyTorch v2.5 and v2.7.1. Omission of profiler.stop() can cause torch.profiler.profile (PythonTracer) to crash or hang during finalization, leading to a Denial of Service (Do


6. torch 2.12.0

CVE: PYSEC-2025-194
Fixed in:

A vulnerability classified as critical has been found in PyTorch 2.6.0. This affects the function torch.jit.script. The manipulation leads to memory corruption. It is possible to launch the attack on


7. torch 2.12.0

CVE: PYSEC-2025-196
Fixed in:

A vulnerability classified as problematic has been found in PyTorch 2.6.0. Affected is the function torch.jit.jit_module_from_flatbuffer. The manipulation leads to memory corruption. Local access is r


8. torch 2.12.0

CVE: PYSEC-2025-195
Fixed in:

A vulnerability classified as critical was found in PyTorch 2.6.0. This vulnerability affects the function torch.lstm_cell. The manipulation leads to memory corruption. The attack needs to be approach


9. torch 2.12.0

CVE: PYSEC-2025-193
Fixed in:

A vulnerability was found in PyTorch 2.6.0. It has been rated as critical. Affected by this issue is the function torch.nn.utils.rnn.unpack_sequence. The manipulation leads to memory corruption. Attac


10. torch 2.12.0

CVE: PYSEC-2025-192
Fixed in:

A vulnerability was found in PyTorch 2.6.0. It has been declared as critical. Affected by this vulnerability is the function torch.nn.utils.rnn.pad_packed_sequence. The manipulation leads to memory co


13 more vulnerabilities not shown. Update dependencies to fix these issues.

Powered by Codity.ai · Docs

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

License Compliance Scan

Metric Value
Packages Scanned 469
High Risk (Strong Copyleft) 0
Medium Risk (Weak Copyleft) 8
Low Risk (Permissive) 408
Unknown License 53

Weak copyleft licenses found - verify compatibility

Some packages have unknown licenses - manual review required

Medium Risk Licenses - 8 packages

MPL-2.0 (6 packages):

  • github.com/hashicorp/errwrap 1.1.0
  • github.com/hashicorp/go-multierror 1.1.1
  • github.com/hashicorp/golang-lru 1.0.2
  • github.com/hashicorp/golang-lru/v2 2.0.7
  • github.com/libp2p/go-yamux/v4 4.0.1
  • github.com/shoenig/go-m1cpu 0.1.6

Mozilla Public License 2.0 (MPL 2.0) (2 packages):

  • TTS 0.22.0
  • certifi 2024.7.4
Unknown Licenses - 53 packages
  • eng_to_ipa 0.0.2
  • github.com/marten-seemann/tcp 0.0.0-20210406111302-dfbc87cc63fd
  • github.com/minio/sha256-simd 1.0.1
  • github.com/miekg/dns 1.1.61
  • github.com/mikioh/tcpinfo 0.0.0-20190314235526-30a79bb1804b
  • github.com/mikioh/tcpopt 0.0.0-20190314235656-172688c1accc
  • github.com/moby/term 0.5.0
  • github.com/moby/sys/sequential 0.5.0
  • github.com/mudler/water 0.0.0-20221010214108-8c7313014ce0
  • github.com/multiformats/go-base32 0.1.0
  • github.com/nwaples/rardecode 1.1.0
  • github.com/olekukonko/tablewriter 0.0.5
  • github.com/opencontainers/go-digest 1.0.0
  • github.com/opencontainers/image-spec 1.1.0
  • github.com/opencontainers/runc 1.1.12
  • github.com/opencontainers/runtime-spec 1.2.0
  • github.com/opentracing/opentracing-go 1.2.0
  • github.com/pbnjay/memory 0.0.0-20210728143218-7b4eea64cf58
  • github.com/peterbourgon/diskv 2.0.1+incompatible
  • github.com/pierrec/lz4/v4 4.1.2

...and 33 more

Powered by Codity.ai · Docs

@codity-dm

codity-dm Bot commented May 21, 2026

Copy link
Copy Markdown

Code Quality Report — test-org-codity/LocalAI · PR #3

Scanned: 2026-05-21 11:31 UTC | Score: 55/100 | Provider: github

Executive Summary

Severity Count
Critical 0
High 2
Medium 3
Low 1
Top Findings

[CQ-LLM-001] core/p2p/federation.go:1 (Complexity · HIGH)

Issue: The 'proxy' function has deep nesting due to the for loop and select statement.
Suggestion: Consider refactoring the function to reduce nesting, possibly by extracting some logic into separate functions.

for {
	select {
	case <-ctx.Done():
		return errors.New("context canceled")
	default:
		log.Debug().Msg("New for connection")
		// Listen for an incoming connection.
		conn, err := l.Accept()
		if err != nil {
			fmt.Println("Error accepting: ", err.Error())
			continue
		}
		
		// Handle connections in a new goroutine, forwarding to the p2p service
		go handleConn(conn)
	}
}

[CQ-LLM-003] core/p2p/federation.go:1 (Error_Handling · HIGH)

Issue: The 'Start' method of 'FederatedServer' does not handle potential errors from 'NewNode' and 'Start' properly.
Suggestion: Ensure that all errors are logged or handled appropriately to avoid silent failures.

n, err := NewNode(fs.p2ptoken)
if err != nil {
	return fmt.Errorf("creating a new node: %w", err)
}

[CQ-LLM-002] core/p2p/federation.go:1 (Duplication · MEDIUM)

Issue: The 'copyStream' function is duplicated in both 'federation.go' and 'p2p.go'.
Suggestion: Remove the duplicate 'copyStream' function from 'p2p.go' and ensure it is only defined in one place.

func copyStream(closer chan struct{}, dst io.Writer, src io.Reader) {
	defer func() { closer <- struct{}{} }() // connection is closed, send signal to stop proxy
	io.Copy(dst, src)
}

[CQ-LLM-004] core/p2p/federation.go:1 (Documentation · MEDIUM)

Issue: Missing documentation for public methods such as 'Start' and 'proxy'.
Suggestion: Add docstrings to public methods to describe their purpose and usage.

func (fs *FederatedServer) Start(ctx context.Context) error {
	// TODO: Add documentation
}

[CQ-LLM-005] core/p2p/federation.go:1 (Maintainability · MEDIUM)

Issue: The use of magic strings like 'context canceled' and 'Error listening' can reduce maintainability.
Suggestion: Define constants for these strings to improve maintainability and readability.

return errors.New("context canceled")

[CQ-008] core/p2p/federation.go:56 (Maintainability · LOW)

Issue: Magic number 10 in code
Suggestion: Extract to a named constant

10*time.Second,

Per-File Breakdown

File Critical High Medium Low Total
core/p2p/federation.go 0 2 3 1 6

Recommendations

  1. Resolve High severity issues, especially error handling gaps and performance bottlenecks.
  • Run automated tests after applying fixes to verify no regressions.

@chay2199 chay2199 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review: refactor: move federated server logic to its own service

The refactor cleanly extracts the federated proxy logic into a FederatedServer struct inside the p2p package, slimming down cli/federated.go to a thin three-liner. The structural intent — struct in an untagged file, implementation behind //go:build p2p, stub in //go:build !p2p — is sound. However, there is a hard compilation error and a crash-level bug that must be fixed before merging.


🔴 Critical — Must Fix

1. Compilation error: ServiceDiscoverer called with wrong arity (federation.go:34)

The actual signature of ServiceDiscoverer in p2p.go is:

func ServiceDiscoverer(ctx context.Context, n *node.Node, token, servicesID string,
    discoveryFunc func(serviceID string, node schema.NodeData), allocate bool) error

But federation.go calls it with only 5 arguments:

if err := ServiceDiscoverer(ctx, n, fs.p2ptoken, FederatedID, nil); err != nil {

The allocate bool parameter is missing. This is a hard build failure under the p2p build tag. Given that handleConn later calls GetAvailableNodes and walks tunnel addresses, allocate almost certainly needs to be true here; without it, nodes will never have a TunnelAddress set (see ensureService), and every connection attempt will silently hit an empty slice.

Fix:

if err := ServiceDiscoverer(ctx, n, fs.p2ptoken, FederatedID, nil, true); err != nil {

2. Nil/empty-slice panic in handleConn (federation.go:97)

tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

If every discovered node reports itself offline, tunnelAddresses is empty and rand.IntN(0) panics, crashing the goroutine with no log or graceful degradation. This was a latent bug in the original Proxy function that this refactor perpetuates — and now the panic happens inside a goroutine with no recovery.

Fix:

if len(tunnelAddresses) == 0 {
    log.Error().Msg("no online tunnel nodes available, dropping connection")
    conn.Close()
    return
}
tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

🟡 Moderate — Should Fix

3. p2p_disabled.go stub is out of sync with the real signature

The stub in p2p_disabled.go is:

func ServiceDiscoverer(ctx context.Context, node *node.Node, token, servicesID string, fn func()) error {

The real signature has a func(serviceID string, node schema.NodeData) callback and an extra allocate bool. These must match exactly or any !p2p build caller will fail to compile. Even if no caller currently hits this code path in non-p2p builds, mismatched stubs are fragile and break the compiler contract.

Fix:

func ServiceDiscoverer(ctx context.Context, n *node.Node, token, servicesID string,
    discoveryFunc func(serviceID string, node schema.NodeData), allocate bool) error {
    return fmt.Errorf("not implemented")
}

4. Stale commented-out code carried over into federation.go (lines ~60–66)

// Retrieve current ID for ip in the blockchain
//_, found := ledger.GetKey(protocol.UsersLedgerKey, node.Host().ID().String())
// If mismatch, update the blockchain
//if !found {
...
//	}

These dead comment blocks were copied verbatim from the old Proxy function. The refactor is a good opportunity to clean them up. Either delete them or, if the conditional logic is intended, restore the actual code and track it as a TODO.


5. handleConn leaks conn on upstream dial failure

tunnelConn, err := net.Dial("tcp", tunnelAddr)
if err != nil {
    log.Error().Err(err).Msg("Error connecting to tunnel")
    return   // ← conn is never closed
}

When the dial fails, the inbound conn is never closed, leaking a file descriptor on every failed upstream connection.

Fix: Add conn.Close() before returning in the error path.


🟢 Positive Observations

  • Architecture is correct. The split between federatedServer.go (no tag — struct only), federation.go (p2p tag — impl), and p2p_disabled.go (!p2p tag — stub) follows the established pattern in this package precisely.
  • cli/federated.go is now a clean 3-line delegate — this is the right call and makes the CLI layer trivially testable.
  • copyStream consolidation is correct. Removing it from p2p.go and defining it once in federation.go (same build tag, same package) is clean; allocateLocalService in p2p.go calls copyStream and both files share the p2p tag, so the symbol is visible at compile time.
  • handleConn extraction improves readability and opens the door to unit testing the routing logic independently.

Summary

# Severity File Issue
1 🔴 Blocker federation.go:34 ServiceDiscoverer called with 5 args, needs 6 — won't compile under p2p tag
2 🔴 Blocker federation.go:97 Panic when tunnelAddresses is empty
3 🟡 Should Fix p2p_disabled.go ServiceDiscoverer stub signature doesn't match real function
4 🟡 Should Fix federation.go:60–66 Dead commented-out code should be removed
5 🟡 Should Fix federation.go:93 conn leaked on upstream dial failure

@chay2199 chay2199 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review: refactor — move federated server logic to its own service

Overall: The structural intent is sound — extracting the federated proxy into its own p2p.FederatedServer type is a clear improvement over the CLI carrying that logic. However, the PR introduces one critical compilation error and a latent panic, and leaves a stub signature inconsistency that will quietly rot.


🔴 Critical — Compilation Error

federation.go:27 — Wrong arity calling ServiceDiscoverer

// federation.go (new, p2p-tagged)
if err := ServiceDiscoverer(ctx, n, fs.p2ptoken, FederatedID, nil); err != nil {

The actual signature in p2p.go (also p2p-tagged) is:

func ServiceDiscoverer(
    ctx context.Context,
    n *node.Node,
    token, servicesID string,
    discoveryFunc func(serviceID string, node schema.NodeData),
    allocate bool,          // ← missing from the call site
) error

The call passes 5 arguments but the function requires 6. This will fail to compile with the p2p build tag. The allocate flag likely should be false here since the federated server is proxying outbound, not allocating a local tunnel.

Fix:

if err := ServiceDiscoverer(ctx, n, fs.p2ptoken, FederatedID, nil, false); err != nil {

🟠 Bug — Panic on Empty Node List

federation.go:92 — Unguarded index into potentially empty slice

tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

If no nodes are online, tunnelAddresses will be empty and rand.IntN(0) panics. This was a pre-existing problem in the old federated.go closure, but migrating it into a named function is a good opportunity to fix it rather than carry the bug forward.

Fix:

if len(tunnelAddresses) == 0 {
    log.Error().Msg("No online tunnel addresses available")
    conn.Close()
    return
}
tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

🟡 Maintenance Hazard — Stub Signature Divergence in p2p_disabled.go

The !p2p stub still uses the old ServiceDiscoverer signature:

// p2p_disabled.go
func ServiceDiscoverer(ctx context.Context, node *node.Node, token, servicesID string, fn func()) error {

The real implementation now takes discoveryFunc func(serviceID string, node schema.NodeData), allocate bool. These compile in mutually exclusive build variants so there's no immediate error — but any future caller in non-build-tagged code would be forced to pick one signature and silently break the other build. Please keep the stub in sync:

func ServiceDiscoverer(ctx context.Context, node *node.Node, token, servicesID string, discoveryFunc func(string, schema.NodeData), allocate bool) error {
    return fmt.Errorf("not implemented")
}

🟡 Design Note — handleConn Has No Context Awareness

handleConn(conn net.Conn) is a detached goroutine with no way to be interrupted if the parent ctx is cancelled (e.g. on shutdown). Since this is now a named function it's worth threading the context through:

func handleConn(ctx context.Context, conn net.Conn) { ... }

And use net.Dialer.DialContext instead of net.Dial so the outbound connection respects cancellation.


✅ What's Done Well

  • Build tag separation is correct: federatedServer.go carries the struct (no tag, always compiled), federation.go carries the p2p-only implementation, and p2p_disabled.go carries the stub — idiomatic Go for conditional compilation.
  • Error message fix: the second error in Start now correctly says "starting a new node" instead of the copy-paste "creating a new node".
  • copyStream removal from p2p.go is safe — it's now defined in federation.go (same package, same build tag), so proxyP2PConnection in p2p.go will still resolve it at compile time.
  • The cli/federated.go simplification from ~120 lines to 3 is exactly what a good refactor looks like.

Summary

Severity File Issue
🔴 Critical core/p2p/federation.go:27 ServiceDiscoverer called with 5 args, needs 6 — compile error
🟠 Bug core/p2p/federation.go:92 Panic when no online nodes (rand.IntN(0))
🟡 Maintenance core/p2p/p2p_disabled.go ServiceDiscoverer stub has stale/mismatched signature
🟡 Design core/p2p/federation.go handleConn ignores context, cannot be cleanly cancelled on shutdown

The compilation error must be fixed before merging. The panic fix is strongly recommended given this is network-facing connection-handling code.

@chay2199 chay2199 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review: "refactor: move federated server logic to its own service"

The overall direction is solid — extracting the inline Proxy/copyStream logic from cli/federated.go into a proper FederatedServer type in core/p2p follows a cleaner separation of concerns, and the build-tag discipline (//go:build p2p on federation.go, stub in p2p_disabled.go) is the right approach. However, there are two compile-breaking issues and a panic that must be fixed before merge.


🔴 Critical: ServiceDiscoverer argument mismatch — compile error under p2p tag

In federation.go, the call is:

if err := ServiceDiscoverer(ctx, n, fs.p2ptoken, FederatedID, nil); err != nil {

That passes 5 arguments. But the actual signature in p2p.go (unchanged by this PR) is:

func ServiceDiscoverer(
    ctx context.Context,
    n *node.Node,
    token, servicesID string,
    discoveryFunc func(serviceID string, node schema.NodeData),
    allocate bool,               // ← 6th parameter, omitted in call
) error

This will fail to compile under the p2p build tag. The missing allocate bool argument needs to be passed (likely false for the federated server use case, since it only discovers, it doesn't allocate).


🔴 Critical: p2p_disabled.go stub signature doesn't match the real function

The newly added stub in p2p_disabled.go:

func ServiceDiscoverer(ctx context.Context, node *node.Node, token, servicesID string, fn func()) error {

has a different signature from the real implementation — wrong parameter count (5 vs 6), and fn func() instead of discoveryFunc func(serviceID string, node schema.NodeData). Any code compiled without the p2p tag that calls ServiceDiscoverer with the real signature will fail. The stub must exactly mirror the real signature:

func ServiceDiscoverer(ctx context.Context, n *node.Node, token, servicesID string, discoveryFunc func(serviceID string, node schema.NodeData), allocate bool) error {
    return fmt.Errorf("not implemented")
}

🟠 High: Panic when no nodes are online in handleConn

tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

If all known nodes are offline, tunnelAddresses is empty and rand.IntN(0) panics. This code path is reachable in normal operation (e.g. transient network issues). Add a guard:

if len(tunnelAddresses) == 0 {
    log.Error().Msg("No online tunnel nodes available")
    conn.Close()
    return
}

This was also present in the original Proxy goroutine — the refactor is a good opportunity to fix this pre-existing bug.


🟡 Medium: handleConn cannot respect context cancellation

go handleConn(conn)

handleConn has no context.Context parameter. Long-lived proxy connections (the two copyStream goroutines) will outlive any context cancellation — e.g. a graceful shutdown signal. The signature should become handleConn(ctx context.Context, conn net.Conn), and the blocking <-closer should be wrapped with a select on ctx.Done().


🟡 Medium: CLI context discarded — context.Background() used instead

In federated.go:

func (f *FederatedCLI) Run(ctx *cliContext.Context) error {
    fs := p2p.NewFederatedServer(f.Address, p2p.FederatedID, f.Peer2PeerToken)
    return fs.Start(context.Background())  // ← ignores the CLI context
}

The cliContext.Context should carry cancellation signals (SIGINT, etc.). fs.Start should receive a properly derived context from the CLI context, not a fresh background one. This was a bug in the original code and should be fixed here.


🟢 Minor: Leftover commented-out code

federation.go carries over several stale comments from the original Proxy function:

//_, found := ledger.GetKey(protocol.UsersLedgerKey, node.Host().ID().String())
// If mismatch, update the blockchain
//if !found {
//  }

These should be removed or converted to a documented // TODO.


🟢 Minor: fmt.Println for error logging

fmt.Println("Error accepting: ", err.Error())

The surrounding code uses zerolog. This should be:

log.Error().Err(err).Msg("Error accepting connection")

✅ What's done well

  • The struct/method split across federatedServer.go (no build tag, struct only) + federation.go (p2p tag, implementation) + p2p_disabled.go stub is the correct pattern for conditional compilation in this codebase.
  • The error message fix ("starting a new node" vs the copy-paste "creating a new node") on the n.Start error path is a good catch.
  • Moving copyStream from p2p.go to federation.go scopes it to where it's actually used.

Bottom line: The two compile errors (argument count mismatch + stub signature) and the handleConn panic must be fixed before merge. The context propagation issue should also be addressed since this PR already touches that code path.

@chay2199 chay2199 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review: Federated Server Refactor

Overall this is a clean, well-motivated refactor. Moving the Proxy / copyStream logic out of the CLI layer and into a proper FederatedServer service type in the p2p package makes the separation of concerns much cleaner, and the //go:build p2p / !p2p stub pattern is used correctly. A few issues worth addressing before merge:


🔴 Potential Panic — empty tunnelAddresses slice

core/p2p/federation.go, handleConn()

tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))]

If no peers are currently online, tunnelAddresses will be empty and rand.IntN(0) panics. This was present in the original cli/federated.go code but this refactor is a good opportunity to fix it:

if len(tunnelAddresses) == 0 {
    log.Error().Msg("No online tunnel nodes available")
    conn.Close()
    return
}

🔴 Ignored error — potential nil-pointer dereference on ledger

core/p2p/federation.go, proxy()

ledger, _ := node.Ledger()

The error from node.Ledger() is silently discarded. If Ledger() returns nil, err, the subsequent ledger.Announce(...) call will panic. The same pattern exists in p2p.go's nodeAnnounce / proxyP2PConnection, but those callers have been present longer. Suggest:

ledger, err := node.Ledger()
if err != nil {
    log.Error().Err(err).Msg("Failed to get ledger")
    return err
}

🟡 handleConn hardcodes FederatedID — coupling concern

core/p2p/federation.go

func handleConn(conn net.Conn) {
    for _, v := range GetAvailableNodes(FederatedID) {

handleConn is a free function that reaches directly for the package-level FederatedID constant. Since FederatedServer already carries fs.service, converting this to a method would decouple it and make the service ID explicit:

func (fs *FederatedServer) handleConn(conn net.Conn) {
    for _, v := range GetAvailableNodes(fs.service) {

The goroutine spawn in proxy would become go fs.handleConn(conn). This also makes the code easier to test in isolation.


🟡 fmt.Println instead of structured logging

core/p2p/federation.go, proxy()

fmt.Println("Error accepting: ", err.Error())

The rest of the file (and codebase) uses zerolog. This line should be:

log.Error().Err(err).Msg("Error accepting connection")

🟢 Minor — p2ptoken field name inconsistency

In federatedServer.go, the constructor parameter is p2pToken (camelCase with capital T) but the struct field is p2ptoken (all lowercase). While not a bug, making the field p2pToken would be more idiomatic and consistent with the parameter name.


✅ Positives

  • cli/federated.go is now beautifully simple — 3 lines of logic instead of 100+.
  • The build-tag pattern (federation.go for the real impl, stub in p2p_disabled.go) is correct and consistent with the rest of the package.
  • context.Background() in the old n.Start() call is replaced with the passed ctx in fs.Start() — a real correctness improvement for context cancellation propagation.
  • copyStream moving from p2p.go to federation.go is correct; both are //go:build p2p, so proxyP2PConnection in p2p.go can still resolve it within the same package build.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants