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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

### Breaking

- [Breaking] **`open` mode does not start when it cannot block the cloud metadata endpoint** — with `block_metadata_endpoint = true` (the default) and no usable nft (`use_sudo = false`, nft not installed or no passwordless sudo for it, e.g. on Colima), or when the nft rules fail, `coi shell`, `coi run` and `coi container start` warned and ran the container with 169.254.0.0/16 reachable. They now fail with the reason and the fix, and stop the container. Make nft usable (`coi health --fix`), or set `block_metadata_endpoint = false` in `~/.coi/config.toml`. `coi health` no longer reports nft as not required for open mode.
- [Breaking] **Host tool configs that run without a prompt are read-only in the container when present** — pre-commit, lefthook, MCP (`.mcp.json`), Gemini, Cursor hooks, JetBrains (`.idea/`), dev container, npm, yarn, pnpm, irb, pry and mise files that exist at session start can no longer be edited from inside the container, and in-container `git checkout` or `pull` cannot update a tracked one: change it on the host, or opt out with `writable_paths` in `~/.coi/config.toml`. An absent one can still be created.
- [Breaking] **The audit log holds policy records, also without monitoring** — `jq 'select(.id != null)'` on `~/.coi/audit/<container>.jsonl` selected only threat events; it now also selects policy records: add `and .category != "policy"`. `coi audit <container>` for a container coi set up without monitoring failed with `no audit log found`; it now prints the container's policy records.

Expand Down
7 changes: 4 additions & 3 deletions install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -365,9 +365,10 @@ setup_nft_sudoers() {

# Ask before adding a passwordless-sudo rule (a security-relevant change).
# It is what lets Coi apply network isolation (restricted/allowlist modes)
# without a password prompt; declining leaves open mode working.
# without a password prompt; declining leaves open mode working only with
# block_metadata_endpoint = false.
if ! user_agrees " Configure passwordless sudo for nft — needed for network isolation? [Y/n]: "; then
echo -e "${YELLOW}⚠ Skipped: without passwordless nft, restricted/allowlist network modes won't work (open mode still does).${NC}"
echo -e "${YELLOW}⚠ Skipped: without passwordless nft, restricted/allowlist network modes won't work, and open mode needs block_metadata_endpoint = false.${NC}"
echo -e " Enable later: ${BLUE}coi health --fix${NC}"
return
fi
Expand All @@ -389,7 +390,7 @@ check_nft() {
echo -e "${YELLOW}⚠ nft not found${NC}"
echo ""
echo " Network isolation (restricted/allowlist modes) requires nftables."
echo " Without it, you can still use open mode."
echo " Without it, you can still use open mode with block_metadata_endpoint = false."
echo ""

if [ "$NONINTERACTIVE" = "1" ]; then
Expand Down
34 changes: 18 additions & 16 deletions internal/cli/bridge_forward_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ func TestIsolateStartedContainer_ContainerBridge(t *testing.T) {

// coi run in open mode installs the metadata reject under
// block_metadata_endpoint and returns it for teardown; without the setting
// nothing is installed. When the reject cannot be installed, stderr says so.
// nothing is installed. When the reject cannot be installed, coi run fails
// and says why.
func TestApplyNetworkIsolation_OpenMetadataBlock(t *testing.T) {
off := false
for _, tc := range []struct {
Expand All @@ -110,12 +111,12 @@ func TestApplyNetworkIsolation_OpenMetadataBlock(t *testing.T) {
useSudo *bool
nftFails bool
reject bool
warning string
fail string
}{
{name: "blocked", block: true, reject: true},
{name: "not blocked", block: false},
{name: "nft script fails", block: true, nftFails: true, warning: "block_metadata_endpoint is not enforced in open mode: nft failed"},
{name: "no usable nft", block: true, useSudo: &off, warning: "block_metadata_endpoint is not enforced in open mode: nft is not usable"},
{name: "nft script fails", block: true, nftFails: true, fail: "could not add the nft rules"},
{name: "no usable nft", block: true, useSudo: &off, fail: "nft is not usable"},
} {
t.Run(tc.name, func(t *testing.T) {
scriptExit := 0
Expand All @@ -131,25 +132,26 @@ func TestApplyNetworkIsolation_OpenMetadataBlock(t *testing.T) {
cfg.Network.Mode = config.NetworkModeOpen
cfg.Network.BlockMetadataEndpoint = &tc.block
cfg.Network.UseSudo = tc.useSudo
var nm networkTeardown
var err error
stderr := captureOutput(t, &os.Stderr, func() {
nm, err = (&App{cfg: cfg}).applyNetworkIsolation(t.Context(), "coi-open-run")
})
nm, err := (&App{cfg: cfg}).applyNetworkIsolation(t.Context(), "coi-open-run")
if tc.fail != "" {
if err == nil || nm != nil {
t.Fatalf("err = %v, teardown = %v; want an error and no teardown", err, nm != nil)
}
for _, want := range []string{"cannot block the cloud metadata endpoint", tc.fail, "block_metadata_endpoint = false"} {
if !strings.Contains(err.Error(), want) {
t.Errorf("error missing %q:\n%v", want, err)
}
}
return
}
if err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(sudoLog)
reject := strings.Contains(string(data), "ip saddr 10.99.0.5 ip daddr 169.254.0.0/16")
if (reject && !tc.nftFails) != tc.reject || (nm != nil) != tc.reject {
if reject != tc.reject || (nm != nil) != tc.reject {
t.Errorf("metadata reject = %v, teardown = %v, want %v; sudo calls:\n%s", reject, nm != nil, tc.reject, data)
}
if tc.warning == "" && strings.Contains(stderr, "not enforced") {
t.Errorf("unexpected warning: %q", stderr)
}
if tc.warning != "" && !strings.Contains(stderr, tc.warning) {
t.Errorf("stderr = %q, want %q", stderr, tc.warning)
}
})
}
}
31 changes: 31 additions & 0 deletions internal/cli/container_isolate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package cli

import (
"os"
"strings"
"testing"
)

// coi container start and launch stop an open-mode container when
// block_metadata_endpoint cannot be enforced (no usable nft): open mode puts
// no boot block on them, so only the stop keeps it from running unfiltered.
func TestContainerStartLaunch_OpenMetadataNotEnforcedStops(t *testing.T) {
for _, args := range [][]string{
{"container", "start", "coi-abc12345-1"},
{"container", "launch", "coi-default", "coi-abc12345-1"},
} {
t.Run(args[1], func(t *testing.T) {
setupProfilesHome(t, nil, "[network]\nmode = \"open\"\nuse_sudo = false\n")
logPath := fakeIncusCases(t, "coi-abc12345-1", reasonConfig, "RUNNING", "")

err := executeArgs(t, args...)
if err == nil || !strings.Contains(err.Error(), "container stopped") || !strings.Contains(err.Error(), "nft is not usable") {
t.Fatalf("err = %v, want the metadata error and the stop", err)
}
b, _ := os.ReadFile(logPath)
if !strings.Contains(string(b), "stop coi-abc12345-1") {
t.Errorf("container not stopped; calls:\n%s", b)
}
})
}
}
7 changes: 3 additions & 4 deletions internal/cli/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -869,10 +869,9 @@ func (a *App) applyNetworkIsolation(ctx context.Context, containerName string) (
}
var block *network.OpenMetadataBlock
if config.BoolVal(networkConfig.BlockMetadataEndpoint) {
var warnings []string
block, warnings = network.ApplyOpenMetadataBlock(&networkConfig, containerName)
for _, w := range warnings {
fmt.Fprintln(os.Stderr, w)
var err error
if block, err = network.ApplyOpenMetadataBlock(&networkConfig, containerName); err != nil {
return nil, fmt.Errorf("failed to setup network isolation: %w", err)
}
}
network.RecordPolicy(stderrLogFn, containerName, &networkConfig, block != nil)
Expand Down
2 changes: 1 addition & 1 deletion internal/cli/state_reason_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func TestUserStop_OtherFailureWarns(t *testing.T) {
const reasonConfig = "config:\n user.coi.state_reason: user\n user.coi.state_reason_at: \"2026-11-28T03:00:00Z\"\ndevices: {}\n"

func TestContainerStart_ClearsReason(t *testing.T) {
setupProfilesHome(t, nil, "[network]\nmode = \"open\"\nuse_sudo = false\n")
setupProfilesHome(t, nil, "[network]\nmode = \"open\"\nuse_sudo = false\nblock_metadata_endpoint = false\n")
logPath := fakeIncusCases(t, "coi-abc12345-1", reasonConfig, "RUNNING", "")

if err := executeArgs(t, "container", "start", "coi-abc12345-1"); err != nil {
Expand Down
2 changes: 1 addition & 1 deletion internal/config/config.starter.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
[network]
# mode = "restricted" # restricted | open | allowlist
# block_private_networks = true # block RFC1918 / 100.64.0.0/10 from the container
# block_metadata_endpoint = true # block 169.254.0.0/16 (cloud metadata/IAM), every mode
# block_metadata_endpoint = true # block 169.254.0.0/16 (cloud metadata/IAM), every mode; needs nft
# allow_local_network_access = false
# allow_host_access = false # let the container reach services on the host itself
# refresh_interval_minutes = 30 # re-resolve allowlist domains (allowlist mode)
Expand Down
18 changes: 12 additions & 6 deletions internal/health/checks_network.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,13 @@ func CheckNft(netCfg config.NetworkConfig) HealthCheck {
"use_sudo": sudoAllowed,
}

if mode == config.NetworkModeOpen {
// Open mode needs nft only for block_metadata_endpoint: coi refuses to
// start when it cannot enforce it.
if mode == config.NetworkModeOpen && !config.BoolVal(netCfg.BlockMetadataEndpoint) {
return HealthCheck{
Name: "nft",
Status: StatusOK,
Message: "nft not required for open mode",
Message: "nft not required for open mode with block_metadata_endpoint = false",
Details: details,
}
}
Expand All @@ -138,19 +140,23 @@ func CheckNft(netCfg config.NetworkConfig) HealthCheck {
// with an incompatible mode. Surface it as a warning (not a hard failure)
// pointing at the fix, rather than nagging about configuring sudo.
if !sudoAllowed {
message := fmt.Sprintf("use_sudo=false but network mode is %q, which needs nft — set [network] mode = \"open\" and block_metadata_endpoint = false (restricted/allowlist require passwordless sudo)", mode)
if mode == config.NetworkModeOpen {
message = "use_sudo=false but block_metadata_endpoint = true needs nft in open mode — set [network] block_metadata_endpoint = false"
}
return HealthCheck{
Name: "nft",
Status: StatusWarning,
Message: fmt.Sprintf("use_sudo=false but network mode is %q, which needs nft — set [network] mode = \"open\" (restricted/allowlist require passwordless sudo)", mode),
Message: message,
Details: details,
}
}

// Required for restricted/allowlist modes
// Required for restricted/allowlist modes, and open mode's metadata block
if !installed {
message := fmt.Sprintf("nft not installed (required for %s mode) — install with: sudo apt install nftables", mode)
if isColima {
message = "nft not installed — on Colima, set mode = \"open\" in [network] section of your config.toml"
message = "nft not installed — on Colima, set mode = \"open\" and block_metadata_endpoint = false in [network] section of your config.toml"
}
return HealthCheck{
Name: "nft",
Expand All @@ -163,7 +169,7 @@ func CheckNft(netCfg config.NetworkConfig) HealthCheck {
if !available {
message := "nft installed but passwordless sudo not configured — run: coi health --fix"
if isColima {
message = "nft sudo not configured — on Colima, set mode = \"open\" in [network] section of your config.toml"
message = "nft sudo not configured — on Colima, set mode = \"open\" and block_metadata_endpoint = false in [network] section of your config.toml"
}
return HealthCheck{
Name: "nft",
Expand Down
17 changes: 14 additions & 3 deletions internal/health/checks_use_sudo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import (

func boolPtr(b bool) *bool { return &b }

// With use_sudo=false, CheckNft must not hard-fail: open mode is OK, and a mode
// that needs nft (restricted/allowlist) is a warning pointing at open mode —
// never StatusFailed, because the user deliberately opted out of sudo.
// With use_sudo=false, CheckNft must not hard-fail: open mode without
// block_metadata_endpoint is OK, and a mode that needs nft (restricted,
// allowlist, open with block_metadata_endpoint) is a warning pointing at the
// fix — never StatusFailed, because the user deliberately opted out of sudo.
func TestCheckNft_UseSudoFalse(t *testing.T) {
t.Run("open mode is OK", func(t *testing.T) {
r := CheckNft(config.NetworkConfig{Mode: config.NetworkModeOpen, UseSudo: boolPtr(false)})
Expand All @@ -20,6 +21,16 @@ func TestCheckNft_UseSudoFalse(t *testing.T) {
}
})

t.Run("open mode with block_metadata_endpoint warns, not fails", func(t *testing.T) {
r := CheckNft(config.NetworkConfig{Mode: config.NetworkModeOpen, UseSudo: boolPtr(false), BlockMetadataEndpoint: boolPtr(true)})
if r.Status != StatusWarning {
t.Errorf("open + use_sudo=false + block_metadata_endpoint: status = %s, want Warning (%s)", r.Status, r.Message)
}
if !strings.Contains(r.Message, "block_metadata_endpoint = false") || strings.Contains(r.Message, `mode = "open"`) {
t.Errorf("message should point at block_metadata_endpoint = false, not at open mode, got: %s", r.Message)
}
})

t.Run("restricted mode warns, not fails", func(t *testing.T) {
r := CheckNft(config.NetworkConfig{Mode: config.NetworkModeRestricted, UseSudo: boolPtr(false)})
if r.Status != StatusWarning {
Expand Down
2 changes: 1 addition & 1 deletion internal/health/remediation.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ func remediations() []Remediation {
},
{
Check: "nft",
Summary: "Configure passwordless sudo for nft (needed for restricted/allowlist network isolation)",
Summary: "Configure passwordless sudo for nft (needed for restricted/allowlist network isolation and open mode's block_metadata_endpoint)",
Class: FixSafe,
Privileged: true,
// Only when nft is installed but passwordless sudo isn't configured
Expand Down
81 changes: 56 additions & 25 deletions internal/network/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,42 @@ workspace .coi/config.toml cannot turn isolation off):

[network]
mode = "open"
block_metadata_endpoint = false

Open mode blocks the cloud metadata endpoint with nft too, so without nft it
also needs block_metadata_endpoint = false.

If you have deliberately declined passwordless sudo (use_sudo = false), note
that restricted/allowlist modes cannot be enforced without it — use open mode.`

// errMetadataNotEnforced is the user-facing error when open mode cannot
// install the metadata reject of block_metadata_endpoint; %s says why.
const errMetadataNotEnforced = `cannot block the cloud metadata endpoint (169.254.0.0/16) in open mode: %s

block_metadata_endpoint = true (the default) needs nftables (nft) with
passwordless sudo, also in open mode, so coi does not start the container.

To fix this:
1. Install nftables: sudo apt install nftables
2. Configure passwordless sudo for nft (validated with visudo):
coi health --fix
3. Do not set use_sudo = false

Alternatively, allow the metadata endpoint in trusted config
(~/.coi/config.toml, or a profile under ~/.coi/profiles; a workspace
.coi/config.toml cannot turn the block off):

[network]
block_metadata_endpoint = false`

// errNftNotUsable is the errMetadataNotEnforced reason when NftUsable is false.
const errNftNotUsable = "nft is not usable (not installed, no passwordless sudo for it, or use_sudo = false)"

// metadataNotEnforced returns errMetadataNotEnforced with why.
func metadataNotEnforced(why string) error {
return fmt.Errorf(errMetadataNotEnforced, why)
}

// Manager provides high-level network isolation management for containers
type Manager struct {
config *config.NetworkConfig
Expand Down Expand Up @@ -118,15 +150,27 @@ func (m *Manager) setupForContainer(ctx context.Context, containerName string) e
m.logger.Println("Network mode: open (no restrictions)")
}
nftUsable := NftUsable(m.config)
if blockMetadata && !nftUsable {
return metadataNotEnforced(errNftNotUsable)
}
// Add ACCEPT rules via nft so traffic flows even when FORWARD policy is DROP
if nftUsable {
containerIP, err := GetContainerIP(containerName)
if err != nil {
if blockMetadata {
return metadataNotEnforced(fmt.Sprintf("could not get the container IP: %v", err))
}
m.logger.Errorf("Warning: could not get container IP for open mode rules: %v", err)
} else {
m.containerIP = containerIP
m.nft = NewNftManager(containerIP, "")
m.metadataBlocked = m.applyOpenRules(containerIP) && blockMetadata
if err := m.applyOpenRules(containerIP); err != nil {
if blockMetadata {
return metadataNotEnforced(fmt.Sprintf("could not add the nft rules: %v", err))
}
m.logger.Errorf("Warning: could not add open mode rules: %v", err)
}
m.metadataBlocked = blockMetadata
}
} else if m.config.SudoAllowed() && NeedsIptablesFallback() {
bridgeName, err := containerNetworkName(containerName)
Expand All @@ -141,11 +185,10 @@ func (m *Manager) setupForContainer(ctx context.Context, containerName string) e
}
}
}
if blockMetadata && !m.metadataBlocked {
m.logger.Errorf("Warning: block_metadata_endpoint is not enforced in open mode: no nft rules for the container")
}
// Open mode always lifts the boot block — errors above are non-fatal
// and the user has explicitly opted into unrestricted network access.
// Open mode lifts the boot block: the errors above that do not return
// are non-fatal, as the user has opted into unrestricted network
// access. The metadata block's errors return with the boot block in
// place.
if err := m.applyUserHosts(containerName); err != nil {
return err
}
Expand Down Expand Up @@ -342,19 +385,18 @@ func openModeRuleTexts(ip string, blockMetadata bool) []string {
return append(texts, openModeRuleText(ip))
}

// applyOpenRules installs open mode's rules for ip (openModeCmds) and reports
// whether they are in place. A reused container whose rules are already
// exactly those is left untouched; anything else is replaced in one
// transaction. Non-fatal, like the code it replaces.
func (m *Manager) applyOpenRules(ip string) bool {
// applyOpenRules installs open mode's rules for ip (openModeCmds). A reused
// container whose rules are already exactly those is left untouched; anything
// else is replaced in one transaction.
func (m *Manager) applyOpenRules(ip string) error {
if err := EnsureBaseRules(); err != nil {
m.logger.Errorf("Warning: failed to ensure base rules: %v", err)
}
blockMetadata := config.BoolVal(m.config.BlockMetadataEndpoint)
rules, err := forwardRulesWithComment("coi-" + ip)
if err == nil && ruleTextsEqual(rules, openModeRuleTexts(ip, blockMetadata)) {
m.purgeStaleSideStateForIP(ip)
return true // already in place (a reused container): nothing to do
return nil // already in place (a reused container): nothing to do
}
if len(rules) > 0 && m.containerName != "" {
// Another mode's rules: a running container from an earlier session,
Expand All @@ -366,22 +408,11 @@ func (m *Manager) applyOpenRules(ip string) bool {
cmds := append(deleteChainRuleCmds("forward", rules), openModeCmds(ip, blockMetadata)...)
if runNFTScript(cmds) == nil {
m.purgeStaleSideStateForIP(ip)
return true
return nil
}
}
m.purgeStaleRulesForIP(ip)
if err := runNFTScript(openModeCmds(ip, blockMetadata)); err != nil {
m.logger.Errorf("Warning: could not add open mode rules: %v", err)
return false
}
return true
}

// MetadataUnenforced reports whether SetupForContainer left open mode's
// block_metadata_endpoint without its reject (no usable nft, no container IP,
// or the rules failed), so the grants report does not claim the block.
func (m *Manager) MetadataUnenforced() bool {
return m.config.Mode == config.NetworkModeOpen && config.BoolVal(m.config.BlockMetadataEndpoint) && !m.metadataBlocked
return runNFTScript(openModeCmds(ip, blockMetadata))
}

// ruleTextsEqual reports whether rules are, in order, exactly texts.
Expand Down
Loading
Loading