fix(webui): mark cookies Secure behind a TLS proxy; run gosec in the gate (#1919)

Cookies took Secure from r.TLS, which is nil behind a proxy that terminates
TLS, so sign-in cookies went out without it. Every dashboard cookie now goes
through one builder that reads the scheme the way the origin check does.

The worktree reset and the agent worker's chown walk use os.Root, so a
symlink swapped in mid-walk can't point them outside the worktree.

gosec runs in golangci-lint, tests included. G104, G115, G204 and G304 are
excluded in config; each remaining finding is fixed or suppressed at the site
with its reason.
This commit is contained in:
sam committed 2026-11-13 03:16:15 +11:00
1 parent a3d4b751b9
commit db346b159d
46 files changed
+199 -115

No files matched your search

+7
View File
@@ -42,6 +42,7 @@ linters:
- errorlint
- fatcontext
- forcetypeassert
- gosec
- makezero
- nilerr
- nilnesserr
@@ -128,6 +129,12 @@ linters:
- HACK
- BUG
gosec:
excludes:
- G104 # errcheck covers unchecked errors
- G115 # integer conversions are bounded where they occur
- G204 # running commands is what the tools and workflow steps do
- G304 # file paths come from configuration and confined worktrees
interfacebloat:
max: 8
@@ -11,7 +11,7 @@ import (
func TestTranscriptToolEntryRedactsAndClips(t *testing.T) {
const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhcmNoaWUifQ.c2lnbmF0dXJlc2lnbmF0dXJl"
const pem = "-----BEGIN RSA PRIVATE KEY-----\nMIIEow\n-----END RSA PRIVATE KEY-----"
const pem = "-----BEGIN RSA PRIVATE KEY-----\nMIIEow\n-----END RSA PRIVATE KEY-----" //nolint:gosec // G101: a fake key the redaction must catch.
long := strings.Repeat("x", transcriptFieldLimit+10)
tests := []struct {
name string
+9 -3
View File
@@ -111,13 +111,19 @@ func (h *hybridTrees) HasUncommittedChanges(ctx context.Context, dir string) (bo
var _ workflow.Trees = (*hybridTrees)(nil)
// chownTree recursively lchowns dir to uid:gid.
// chownTree recursively lchowns dir to uid:gid, through a root so a symlink
// swapped in mid-walk cannot point it outside dir.
func chownTree(dir string, uid, gid int) error {
return filepath.WalkDir(dir, func(path string, _ fs.DirEntry, err error) error {
root, err := os.OpenRoot(dir)
if err != nil {
return err
}
defer func() { _ = root.Close() }()
return fs.WalkDir(root.FS(), ".", func(path string, _ fs.DirEntry, err error) error {
if err != nil {
return err
}
return os.Lchown(path, uid, gid)
return root.Lchown(path, uid, gid)
})
}
+2 -2
View File
@@ -43,13 +43,13 @@ func TestModelEgressResolvesProviderSecretRefs(t *testing.T) {
},
{
name: "an env-only provider keeps its binding",
provider: config.Provider{Class: "openai", APIKeyEnv: "PROVIDER_ENV_KEY"},
provider: config.Provider{Class: "openai", APIKeyEnv: "PROVIDER_ENV_KEY"}, //nolint:gosec // G101: env var and secret names, not values.
bindings: []config.CredentialBinding{{Service: "used", Org: "org-test", Secret: config.SecretRef{Engine: "env", Key: "PROVIDER_KEY"}}},
wantEnv: "PROVIDER_ENV_KEY",
},
{
name: "an env-only provider without a binding is refused",
provider: config.Provider{Class: "openai", APIKeyEnv: "PROVIDER_ENV_KEY"},
provider: config.Provider{Class: "openai", APIKeyEnv: "PROVIDER_ENV_KEY"}, //nolint:gosec // G101: env var and secret names, not values.
wantErr: "no credential binding",
},
}
@@ -6,7 +6,7 @@ import (
"errors"
"log/slog"
"net/http"
"net/http/cgi"
"net/http/cgi" //nolint:gosec // G504: serves git http-backend; the Httpoxy CVE predates Go 1.6.3.
"net/http/httptest"
"os"
"os/exec"
+9 -6
View File
@@ -16,8 +16,10 @@ func TestUpdateTopologyRefusal(t *testing.T) {
root := t.TempDir()
config := filepath.Join(root, "config.toml")
required := releaseupdate.Topology{Units: []string{"archie-state-store", "archie-gateway", "archied"}, ConfigSections: []string{"services.state", "services.gateway"}}
writeUpdateFixture(t, config, "[services.state]\ntarget='localhost:9090'\n")
writeUpdateFixture(t, filepath.Join(root, "systemctl"), "#!/bin/sh\nprintf 'archied.service enabled enabled\\n'\n")
if err := os.WriteFile(config, []byte("[services.state]\ntarget='localhost:9090'\n"), 0o600); err != nil {
t.Fatal(err)
}
writeScript(t, filepath.Join(root, "systemctl"), "#!/bin/sh\nprintf 'archied.service enabled enabled\\n'\n")
t.Setenv("PATH", root+":"+os.Getenv("PATH"))
var output bytes.Buffer
if err := checkUpdateTopology(t.Context(), config, required, true, &output); err == nil {
@@ -39,8 +41,8 @@ func TestResumeUpdate(t *testing.T) {
t.Fatal(err)
}
called := filepath.Join(root, "called")
writeUpdateFixture(t, filepath.Join(root, "systemd-run"), "#!/bin/sh\nprintf '%s\\n' \"$@\" > '"+called+"'\n")
writeUpdateFixture(t, filepath.Join(root, "systemctl"), "#!/bin/sh\n")
writeScript(t, filepath.Join(root, "systemd-run"), "#!/bin/sh\nprintf '%s\\n' \"$@\" > '"+called+"'\n")
writeScript(t, filepath.Join(root, "systemctl"), "#!/bin/sh\n")
t.Setenv("PATH", root+":"+os.Getenv("PATH"))
lock, err := os.OpenFile(filepath.Join(root, "lock"), os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
@@ -69,9 +71,10 @@ func TestResumeUpdate(t *testing.T) {
}
}
func writeUpdateFixture(t *testing.T, path, data string) {
// writeScript writes a stand-in for a host command the update runs.
func writeScript(t *testing.T, path, data string) {
t.Helper()
if err := os.WriteFile(path, []byte(data), 0o700); err != nil {
if err := os.WriteFile(path, []byte(data), 0o700); err != nil { //nolint:gosec // G306: a script needs the execute bit.
t.Fatal(err)
}
}
+1 -1
View File
@@ -26,7 +26,7 @@ import (
const telegramCredential = "telegram"
// credentialBindingsKind is the control-plane resource holding the bindings.
const credentialBindingsKind = "credential-bindings"
const credentialBindingsKind = "credential-bindings" //nolint:gosec // G101: a credential service name, not a credential.
// orgChannelSource is where the Messaging Service learns which orgs run a
// channel and how they are bound. *controlplanerpc.Client satisfies the first
+1 -1
View File
@@ -193,5 +193,5 @@ func writeReport(dir, report string) (string, error) {
return "", err
}
path := filepath.Join(dir, "pr-review-"+time.Now().UTC().Format("20060102-150405")+".md")
return path, os.WriteFile(path, []byte(report), 0o644)
return path, os.WriteFile(path, []byte(report), 0o644) //nolint:gosec // G306: a report for the operator to read.
}
+2 -2
View File
@@ -93,7 +93,7 @@ func WriteTaskJSON(workspace string, payload TaskPayload) error {
if err := os.MkdirAll(gitDir, 0o700); err != nil {
return fmt.Errorf("task.json: %w", err)
}
return os.WriteFile(filepath.Join(gitDir, "task.json"), data, 0o644)
return os.WriteFile(filepath.Join(gitDir, "task.json"), data, 0o644) //nolint:gosec // G306: the task container reads its brief as another user.
}
// Pool manages a set of Docker containers running archie-agent.
@@ -699,7 +699,7 @@ func encodeRegistryAuth(credential string) (string, error) {
if auth.Username == "" && auth.Password == "" && auth.IdentityToken == "" && auth.RegistryToken == "" {
return "", errors.New("registry credential names no username, password, identity token or registry token")
}
payload, err := json.Marshal(auth)
payload, err := json.Marshal(auth) //nolint:gosec // G117: the registry credential is meant for the image pull's auth header.
if err != nil {
return "", fmt.Errorf("encode registry credential: %w", err)
}
+2 -2
View File
@@ -54,7 +54,7 @@ func prefetchPRReview(ctx context.Context, f any, owner, repo string, number int
if err != nil {
return fmt.Errorf("prefetch pr-review: %w", err)
}
if err := os.WriteFile(filepath.Join(base, "diff.patch"), []byte(diff), 0o644); err != nil {
if err := os.WriteFile(filepath.Join(base, "diff.patch"), []byte(diff), 0o644); err != nil { //nolint:gosec // G306: the task container reads the diff as another user.
return fmt.Errorf("prefetch pr-review: write diff: %w", err)
}
@@ -66,7 +66,7 @@ func prefetchPRReview(ctx context.Context, f any, owner, repo string, number int
if err != nil {
return fmt.Errorf("prefetch pr-review: encode metadata: %w", err)
}
if err := os.WriteFile(filepath.Join(base, "metadata.json"), metaJSON, 0o644); err != nil {
if err := os.WriteFile(filepath.Join(base, "metadata.json"), metaJSON, 0o644); err != nil { //nolint:gosec // G306: the task container reads the metadata as another user.
return fmt.Errorf("prefetch pr-review: write metadata: %w", err)
}
return nil
+1 -1
View File
@@ -67,7 +67,7 @@ const (
KindModelAlias = "model.alias"
KindProviderNoKey = "provider.no_credential"
KindToolNoBinding = "tool.no_credential"
KindCredentialInvalid = "credential.rejected"
KindCredentialInvalid = "credential.rejected" //nolint:gosec // G101: an alert kind, not a credential.
KindServiceUnhealthy = "service.unhealthy"
KindReleaseAvailable = "release.available"
KindPolicyInvalid = "policy.invalid"
@@ -9,7 +9,7 @@ func TestAuthenticationSettingsRejectUntrustedOrigins(t *testing.T) {
}{
{name: "public TLS", url: "https://archie.example", want: true},
{name: "localhost", url: "http://localhost:8484", want: true},
{name: "userinfo is not an origin", url: "https://user:password@archie.example", want: false},
{name: "userinfo is not an origin", url: "https://user:password@archie.example", want: false}, //nolint:gosec // G101: a fake URL with userinfo, which must be refused.
{name: "URL path cannot change the RP origin", url: "https://archie.example/subpath", want: false},
{name: "query is not an origin", url: "https://archie.example?token=1", want: false},
{name: "complete provider", url: "https://archie.example", issuer: "https://identity.example", client: "archie", audience: "archie", want: true},
@@ -26,6 +26,7 @@ package identity
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//nolint:gosec // G101: the list of passwords sign-up refuses.
const commonPasswords = `
$hex[687474703a2f2f616473]
$hex[687474703a2f2f777777]
@@ -89,7 +89,7 @@ func bundledMigrationURL() string {
// database as an explicit choice, switching to it must generate PGPASSWORD
// into the sink, and keeping must leave the existing URL untouched.
func TestRunParamsDatabaseChoice(t *testing.T) {
const existing = "postgres://operator:secret@db.internal:5432/archie"
const existing = "postgres://operator:secret@db.internal:5432/archie" //nolint:gosec // G101: a fake database URL.
tests := []struct {
name string
@@ -18,6 +18,7 @@ type cloudProvider struct {
apiKeyEnv string
}
//nolint:gosec // G101: env var names, not values.
var cloudProviders = []cloudProvider{
{name: "OpenAI", class: "openai", apiKeyEnv: "OPENAI_API_KEY"},
{name: "Anthropic", class: "anthropic", apiKeyEnv: "ANTHROPIC_API_KEY"},
@@ -4,7 +4,7 @@ import "github.com/samcharles93/archie-core/internal/config"
// CredentialBindingsKind is the resource mapping credential service names to
// org secrets. Applied live on each launch.
const CredentialBindingsKind = "credential-bindings"
const CredentialBindingsKind = "credential-bindings" //nolint:gosec // G101: a resource kind, not a credential.
// credentialBinding is one config.CredentialBinding as the document writes
// it: explicit snake_case json tags, following channel_settings.go /
+1 -1
View File
@@ -97,7 +97,7 @@ func createCA(dir, certPath, keyPath string) (*CA, error) {
if err := os.WriteFile(keyPath, keyPEM, 0o600); err != nil {
return nil, err
}
if err := os.WriteFile(certPath, certPEM, 0o644); err != nil {
if err := os.WriteFile(certPath, certPEM, 0o644); err != nil { //nolint:gosec // G306: a CA certificate is public; its key is written 0600 above.
return nil, err
}
return parseCA(certPEM, keyPEM)
@@ -100,7 +100,7 @@ func TestUsableProviderCredentials(t *testing.T) {
// again.
func TestMergeProvidersKeepsDisabled(t *testing.T) {
merged := mergeProviders(
map[string]config.Provider{"openai": {Class: "openai", APIKeyEnv: "OPENAI_API_KEY"}},
map[string]config.Provider{"openai": {Class: "openai", APIKeyEnv: "OPENAI_API_KEY"}}, //nolint:gosec // G101: an env var name, not a value.
map[string]config.Provider{"openai": {Disabled: true}},
)
if !merged["openai"].Disabled {
@@ -21,9 +21,9 @@ func testProvisionRoles() provisionRoles {
// plan that would leave the runtime role owning schema changes.
func TestParseProvisionURLs(t *testing.T) {
const (
adminURL = "postgres://archie:admin@db.internal/archie"
runtimeURL = "postgres://archie_runtime:runtime@db.internal/archie"
migrationURL = "postgres://archie_migrator:migration@db.internal/archie"
adminURL = "postgres://archie:admin@db.internal/archie" //nolint:gosec // G101: fake database URLs.
runtimeURL = "postgres://archie_runtime:runtime@db.internal/archie" //nolint:gosec // G101: fake database URLs.
migrationURL = "postgres://archie_migrator:migration@db.internal/archie" //nolint:gosec // G101: fake database URLs.
)
tests := []struct {
name string
@@ -75,7 +75,7 @@ func TestParseProvisionURLs(t *testing.T) {
},
{
name: "the same role cannot be runtime and migration",
opts: ProvisionOptions{AdminURL: adminURL, RuntimeURL: runtimeURL, MigrationURL: "postgres://archie_runtime:other@db.internal/archie"},
opts: ProvisionOptions{AdminURL: adminURL, RuntimeURL: runtimeURL, MigrationURL: "postgres://archie_runtime:other@db.internal/archie"}, //nolint:gosec // G101: a fake database URL.
wantErr: "same role",
},
{
@@ -85,7 +85,7 @@ func TestParseProvisionURLs(t *testing.T) {
},
{
name: "a non-PostgreSQL URL is refused",
opts: ProvisionOptions{AdminURL: "mysql://archie:admin@db.internal/archie", RuntimeURL: runtimeURL, MigrationURL: migrationURL},
opts: ProvisionOptions{AdminURL: "mysql://archie:admin@db.internal/archie", RuntimeURL: runtimeURL, MigrationURL: migrationURL}, //nolint:gosec // G101: a fake database URL.
wantErr: "postgres:// URL",
},
{
+1 -1
View File
@@ -130,7 +130,7 @@ func writeEntry(destDir, prefix string, e tarEntry) error {
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return err
}
return os.WriteFile(target, e.data, 0o644)
return os.WriteFile(target, e.data, 0o644) //nolint:gosec // G306: the task container reads the checkout as another user.
default:
// Symlinks, devices, etc: not followed, not written.
return nil
@@ -14,7 +14,7 @@ import (
// at all and there is nothing here to test.
func requireNamespaces(t *testing.T) {
t.Helper()
cmd := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^$")
cmd := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^$") //nolint:gosec // G702: re-runs this test binary.
cmd.SysProcAttr = &syscall.SysProcAttr{
Cloneflags: syscall.CLONE_NEWUSER | syscall.CLONE_NEWNET,
UidMappings: []syscall.SysProcIDMap{{ContainerID: os.Getuid(), HostID: os.Getuid(), Size: 1}},
@@ -103,7 +103,7 @@ func TestMain(m *testing.M) {
func selfDigest(t *testing.T) string {
t.Helper()
binary, err := os.ReadFile(os.Args[0])
binary, err := os.ReadFile(os.Args[0]) //nolint:gosec // G703: reads this test binary.
if err != nil {
t.Fatal(err)
}
@@ -243,7 +243,7 @@ func layerOf(t *testing.T, name string, content []byte) []byte {
// An extension runs only while its package is accepted and the settings enable
// it, and stops the moment either stops being true.
func TestRunnerRunsOnlyWhatIsAcceptedAndEnabled(t *testing.T) {
binary, err := os.ReadFile(os.Args[0])
binary, err := os.ReadFile(os.Args[0]) //nolint:gosec // G703: reads this test binary.
if err != nil {
t.Fatal(err)
}
@@ -85,7 +85,7 @@ func (s *Store) Write(_ context.Context, sk curator.Skill) error {
if info, err := os.Stat(dir); err != nil || !info.IsDir() {
return fmt.Errorf("skillcurator: skill %q does not exist under %s", sk.Name, s.skillsPath())
}
if err := os.WriteFile(s.skillPath(sk.Name), []byte(sk.Content), 0o644); err != nil {
if err := os.WriteFile(s.skillPath(sk.Name), []byte(sk.Content), 0o644); err != nil { //nolint:gosec // G306: agents read skills as another user.
return fmt.Errorf("skillcurator: writing %s: %w", s.skillPath(sk.Name), err)
}
return nil
@@ -14,7 +14,7 @@ func TestModelProviderWireCarriesCredentialRef(t *testing.T) {
t.Parallel()
sent := map[string]config.Provider{
"remote": {
"remote": { //nolint:gosec // G101: env var and secret names, not values.
Class: "deepseek",
BaseURL: "https://example.invalid/v1",
APIKeyEnv: "REMOTE_API_KEY",
+1 -1
View File
@@ -153,7 +153,7 @@ func validateLayer(layer []byte, mediaType string, files []domain.File) error {
return err
}
found[header.Name] = true
if _, err := io.Copy(io.Discard, tarReader); err != nil {
if _, err := io.Copy(io.Discard, tarReader); err != nil { //nolint:gosec // G110: the tar reader is bounded by io.LimitReader(maxPackageBytes).
return err
}
}
+1 -1
View File
@@ -74,7 +74,7 @@ func Publish(ctx context.Context, req PublishRequest) (Statement, error) {
for i, content := range [][]byte{ocispec.DescriptorEmptyJSON.Data, encoded, archive} {
desc := ocispec.DescriptorEmptyJSON
if i > 0 {
desc = layers[i-1]
desc = layers[i-1] //nolint:gosec // G602: i > 0 indexes the two layers built above.
}
if err := pushBlob(ctx, repository, desc, content); err != nil {
return Statement{}, err
+4 -3
View File
@@ -198,7 +198,7 @@ func TestTransaction(t *testing.T) {
server := httptest.NewServer(handler)
defer server.Close()
for _, unit := range testUnits {
writeTestFile(t, filepath.Join(host.bin, unit), versionScript(unit, "1.0.0"))
writeScript(t, filepath.Join(host.bin, unit), versionScript(unit, "1.0.0"))
}
report := filepath.Join(root, "report.json")
tx := &Transaction{
@@ -358,12 +358,13 @@ func versionScript(unit, version string) string {
return fmt.Sprintf("#!/bin/sh\n# %s %s\necho '%s %s'\n", unit, version, unit, version)
}
func writeTestFile(t *testing.T, path, data string) {
// writeScript writes a stand-in for a release binary the transaction runs.
func writeScript(t *testing.T, path, data string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(data), 0o755); err != nil {
if err := os.WriteFile(path, []byte(data), 0o700); err != nil { //nolint:gosec // G306: a script needs the execute bit.
t.Fatal(err)
}
}
+1 -1
View File
@@ -308,7 +308,7 @@ const (
BlockerForgeExtension Blocker = "forge_extension"
// BlockerModelCredential: a model provider the run needs has no usable
// credential.
BlockerModelCredential Blocker = "model_credential"
BlockerModelCredential Blocker = "model_credential" //nolint:gosec // G101: a blocker name, not a credential.
// BlockerModelCredit: a model provider refused the run for want of
// credit or quota on its account.
BlockerModelCredit Blocker = "model_credit"
+1 -1
View File
@@ -117,7 +117,7 @@ func makeWriteExecutor(cwd string, mq *MutationQueue, rt *ReadTracker) Executor
// file, a directory, a symlink, or any other non-regular entry returns false,
// which lets new files skip the overwrite and read-before-write checks.
func isRegularFile(path string) bool {
info, err := os.Stat(path)
info, err := os.Stat(path) //nolint:gosec // G703: callers confine path with isConfined first.
return err == nil && info.Mode().IsRegular()
}
+1 -1
View File
@@ -297,7 +297,7 @@ func (p *Provider) writeMultimodalResult(toolName, summaryText string, media []p
ext := extensionForMimeType(mimeType)
name := fmt.Sprintf("%d%s", i, ext)
path := filepath.Join(subdir, name)
if err := os.WriteFile(path, raw, 0o644); err != nil {
if err := os.WriteFile(path, raw, 0o644); err != nil { //nolint:gosec // G306: the agent reads tool media as another user.
return tools.MultimodalResult{}, fmt.Errorf("MCP tool %s: write media block %d: %w", toolName, i, err)
}
files = append(files, path)
+1 -1
View File
@@ -57,7 +57,7 @@ func TestDenialsRouteRequiresAdmin(t *testing.T) {
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "https://archie.example"+path, nil)
req.Header.Set("X-Archie-CSRF", "1")
req.AddCookie(&http.Cookie{Name: "archie_session", Value: "valid"})
sendCookie(req, "archie_session", "valid")
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != tt.want {
+4 -9
View File
@@ -152,14 +152,13 @@ func (s *Server) signInAccount(w http.ResponseWriter, r *http.Request, email, pa
if s.Log != nil {
s.Log.InfoContext(r.Context(), "account signed in", "identity", value.Identity.ID)
}
s.clearProviderCookie(w)
s.clearCookie(w, r, s.cookies().providerToken, "/")
s.setAccountCookie(w, r, value)
writeJSON(w, map[string]any{"user": value.Identity})
}
func (s *Server) setAccountCookie(w http.ResponseWriter, r *http.Request, value identity.AccountSession) {
scheme, _ := s.expectedOrigin(r)
http.SetCookie(w, &http.Cookie{Name: s.cookies().account, Value: value.Token, Path: "/", HttpOnly: true, Secure: scheme == "https", SameSite: http.SameSiteStrictMode, Expires: value.Expires, MaxAge: int(time.Until(value.Expires).Seconds())})
s.setCookie(w, r, cookie{name: s.cookies().account, value: value.Token, maxAge: int(time.Until(value.Expires).Seconds())})
w.Header().Set("Cache-Control", "no-store")
}
@@ -174,7 +173,7 @@ func (s *Server) handleAccountLogout(w http.ResponseWriter, r *http.Request) {
}
}
for _, name := range []string{s.cookies().account, s.cookies().providerToken} {
http.SetCookie(w, &http.Cookie{Name: name, Path: "/", HttpOnly: true, MaxAge: -1, SameSite: http.SameSiteStrictMode})
s.clearCookie(w, r, name, "/")
}
w.WriteHeader(http.StatusNoContent)
}
@@ -214,7 +213,7 @@ func (s *Server) handleAccountPassword(w http.ResponseWriter, r *http.Request) {
s.writeAccountError(w, err)
return
}
http.SetCookie(w, &http.Cookie{Name: s.cookies().account, Path: "/", MaxAge: -1, HttpOnly: true, SameSite: http.SameSiteStrictMode})
s.clearCookie(w, r, s.cookies().account, "/")
w.WriteHeader(http.StatusNoContent)
}
@@ -356,10 +355,6 @@ func (s *Server) handleAccountRecover(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) clearProviderCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{Name: s.cookies().providerToken, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
}
func (s *Server) authorizeAuthenticationMutation(w http.ResponseWriter, r *http.Request) bool {
if !s.authorizeTaskMutation(w, r) {
return false
+1 -1
View File
@@ -74,7 +74,7 @@ func TestAccountBoundary(t *testing.T) {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Archie-CSRF", tc.csrf)
if tc.cookie != "" {
req.AddCookie(&http.Cookie{Name: "archie_session", Value: tc.cookie})
sendCookie(req, "archie_session", tc.cookie)
}
recorder := httptest.NewRecorder()
srv.Handler().ServeHTTP(recorder, req)
+1 -1
View File
@@ -35,7 +35,7 @@ type ModelReader interface {
// rather than imported so the dashboard package stays a leaf.
const (
providerSettingsKind = "provider-settings"
credentialBindingsKind = "credential-bindings"
credentialBindingsKind = "credential-bindings" //nolint:gosec // G101: a resource kind, not a credential.
)
// providerDoc is the part of one provider-settings entry the read needs: where
+11 -28
View File
@@ -85,19 +85,12 @@ func (s *Server) requireToken(h http.Handler) http.Handler {
http.Error(w, "unauthorised", http.StatusUnauthorized)
return
}
http.SetCookie(w, &http.Cookie{
Name: s.cookies().token,
Value: tok,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
Secure: r.TLS != nil,
})
s.setCookie(w, r, cookie{name: s.cookies().token, value: tok})
clean := *r.URL
q := clean.Query()
q.Del("t")
clean.RawQuery = q.Encode()
http.Redirect(w, r, sameOriginPath(clean.Path, clean.RawQuery), http.StatusSeeOther)
http.Redirect(w, r, sameOriginPath(clean.Path, clean.RawQuery), http.StatusSeeOther) //nolint:gosec // G710: sameOriginPath keeps the redirect on this origin.
return
}
@@ -172,8 +165,8 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
s.refuseUnidentified(w, r, err)
return
}
setFlowCookie(w, r, s.cookies().loginState, state)
setFlowCookie(w, r, s.cookies().loginVerifier, verifier)
s.setFlowCookie(w, r, s.cookies().loginState, state)
s.setFlowCookie(w, r, s.cookies().loginVerifier, verifier)
http.Redirect(w, r, url, http.StatusSeeOther)
}
@@ -211,8 +204,8 @@ func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) {
s.refuseUnidentified(w, r, err)
return
}
clearFlowCookie(w, r, s.cookies().loginState)
clearFlowCookie(w, r, s.cookies().loginVerifier)
s.clearFlowCookie(w, r, s.cookies().loginState)
s.clearFlowCookie(w, r, s.cookies().loginVerifier)
if security, ok := s.Accounts.(identity.AccountSecurity); ok {
principal, resolveErr := s.Principals.PrincipalFor(r.Context(), value.ID)
if resolveErr != nil {
@@ -226,26 +219,16 @@ func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) {
}
s.setAccountCookie(w, r, local)
}
http.SetCookie(w, &http.Cookie{
Name: s.cookies().providerToken, Value: session.Token, Path: "/",
HttpOnly: true, SameSite: http.SameSiteStrictMode, Secure: r.TLS != nil,
})
s.setCookie(w, r, cookie{name: s.cookies().providerToken, value: session.Token})
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func setFlowCookie(w http.ResponseWriter, r *http.Request, name, value string) {
http.SetCookie(w, &http.Cookie{
Name: name, Value: value, Path: "/oauth2",
HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: r.TLS != nil,
MaxAge: loginCookieMaxAge,
})
func (s *Server) setFlowCookie(w http.ResponseWriter, r *http.Request, name, value string) {
s.setCookie(w, r, cookie{name: name, value: value, path: "/oauth2", sameSite: http.SameSiteLaxMode, maxAge: loginCookieMaxAge})
}
func clearFlowCookie(w http.ResponseWriter, r *http.Request, name string) {
http.SetCookie(w, &http.Cookie{
Name: name, Value: "", Path: "/oauth2",
HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: r.TLS != nil, MaxAge: -1,
})
func (s *Server) clearFlowCookie(w http.ResponseWriter, r *http.Request, name string) {
s.setCookie(w, r, cookie{name: name, path: "/oauth2", sameSite: http.SameSiteLaxMode, maxAge: -1})
}
// randomToken returns a fresh URL-safe nonce for a sign-in's state.
@@ -148,7 +148,7 @@ func TestHTTPPolicyCannotBeBypassed(t *testing.T) {
req.Header.Set("X-Archie-CSRF", "1")
want := http.StatusUnauthorized
if signedIn {
req.AddCookie(&http.Cookie{Name: "archie_session", Value: "valid"})
sendCookie(req, "archie_session", "valid")
want = http.StatusForbidden
}
rec := httptest.NewRecorder()
@@ -189,7 +189,7 @@ func TestResourceHistoryNeedsPolicyManagement(t *testing.T) {
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "https://archie.example"+path, nil)
req.Header.Set("X-Archie-CSRF", "1")
req.AddCookie(&http.Cookie{Name: "archie_session", Value: "valid"})
sendCookie(req, "archie_session", "valid")
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != tt.want {
@@ -231,7 +231,7 @@ func TestAuditRoutesFollowTheReadAuditRole(t *testing.T) {
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "https://archie.example"+route.path, nil)
req.Header.Set("X-Archie-CSRF", "1")
req.AddCookie(&http.Cookie{Name: "archie_session", Value: "valid"})
sendCookie(req, "archie_session", "valid")
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != tt.want {
+1 -1
View File
@@ -33,7 +33,7 @@ func TestChatFileDownload(t *testing.T) {
}{
{name: "an offered file is served", token: token, want: http.StatusOK},
{name: "a token nobody was given is refused", token: "0123456789abcdef0123456789abcdef", want: http.StatusNotFound},
{name: "a path is not a token", token: "..%2f..%2fetc%2fpasswd", want: http.StatusNotFound},
{name: "a path is not a token", token: "..%2f..%2fetc%2fpasswd", want: http.StatusNotFound}, //nolint:gosec // G101: a fake file token.
{name: "owner downloads private file", user: "alice", token: private, want: http.StatusOK},
{name: "another person cannot download", user: "bob", token: private, want: http.StatusNotFound},
{name: "unidentified caller cannot download private file", token: private, want: http.StatusNotFound},
+32 -1
View File
@@ -1,6 +1,9 @@
package webui
import "strings"
import (
"net/http"
"strings"
)
// cookieNames are the dashboard's cookie names. Browsers scope cookies by host
// and ignore the port, so each name carries the instance: two instances on
@@ -27,3 +30,31 @@ func newCookieNames(instance string) cookieNames {
}
func (s *Server) cookies() cookieNames { return newCookieNames(s.Instance) }
// cookie is what varies between the dashboard's cookies. Every one is
// HttpOnly, and Secure whenever the browser reached the dashboard over HTTPS.
type cookie struct {
name, value, path string
// sameSite defaults to Strict; the sign-in flow needs Lax to survive the
// provider's redirect back.
sameSite http.SameSite
// maxAge is in seconds; negative deletes the cookie.
maxAge int
}
func (s *Server) setCookie(w http.ResponseWriter, r *http.Request, c cookie) {
if c.path == "" {
c.path = "/"
}
if c.sameSite == 0 {
c.sameSite = http.SameSiteStrictMode
}
http.SetCookie(w, &http.Cookie{ //nolint:gosec // G124: a fixed Secure would stop plain-HTTP deployments signing in.
Name: c.name, Value: c.value, Path: c.path, MaxAge: c.maxAge,
HttpOnly: true, Secure: s.secureRequest(r), SameSite: c.sameSite,
})
}
func (s *Server) clearCookie(w http.ResponseWriter, r *http.Request, name, path string) {
s.setCookie(w, r, cookie{name: name, path: path, maxAge: -1})
}
+50
View File
@@ -0,0 +1,50 @@
package webui
import (
"crypto/tls"
"net/http"
"net/http/httptest"
"testing"
)
// sendCookie attaches a cookie to a request as a browser sends it: a name and
// a value, with none of the attributes a response sets.
func sendCookie(req *http.Request, name, value string) {
req.Header.Add("Cookie", name+"="+value)
}
// TestSessionCookiesSecureBehindProxy pins that a cookie is marked Secure
// whenever the browser reached the dashboard over HTTPS, including through a
// trusted proxy that terminates TLS.
func TestSessionCookiesSecureBehindProxy(t *testing.T) {
tests := []struct {
name string
tls bool
forwarded string
trust bool
wantSecure bool
}{
{"direct https", true, "", false, true},
{"plain http", false, "", false, false},
{"trusted proxy terminating https", false, "https", true, true},
{"untrusted forwarded header", false, "https", false, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &Server{TrustForwardedHeaders: tt.trust}
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil)
if tt.tls {
r.TLS = &tls.ConnectionState{}
}
if tt.forwarded != "" {
r.Header.Set("X-Forwarded-Proto", tt.forwarded)
}
w := httptest.NewRecorder()
s.setOrgCookie(w, r, "acme")
cookies := w.Result().Cookies()
if len(cookies) != 1 || cookies[0].Secure != tt.wantSecure {
t.Fatalf("cookies = %+v, want one with Secure=%v", cookies, tt.wantSecure)
}
})
}
}
+3 -6
View File
@@ -41,14 +41,11 @@ func (s *Server) workspaces() access.WorkspaceLister {
}
func (s *Server) setOrgCookie(w http.ResponseWriter, r *http.Request, id string) {
cookie := &http.Cookie{
Name: s.cookies().org, Value: id, Path: "/",
HttpOnly: true, SameSite: http.SameSiteStrictMode, Secure: r.TLS != nil, MaxAge: orgCookieMaxAge,
}
if id == "" {
cookie.MaxAge = -1
s.clearCookie(w, r, s.cookies().org, "/")
return
}
http.SetCookie(w, cookie)
s.setCookie(w, r, cookie{name: s.cookies().org, value: id, maxAge: orgCookieMaxAge})
}
// handleOrgSelect makes the caller's chosen org the one its tasks, workflows
+1 -1
View File
@@ -484,7 +484,7 @@ func TestOrgSelection(t *testing.T) {
req.Header.Set("Content-Type", "application/json")
}
if tt.cookie != "" {
req.AddCookie(&http.Cookie{Name: s.cookies().org, Value: tt.cookie})
sendCookie(req, s.cookies().org, tt.cookie)
}
rec := httptest.NewRecorder()
orgRoutes(s).ServeHTTP(rec, req)
+3 -4
View File
@@ -40,8 +40,7 @@ func (s *Server) handlePasskeyBegin(w http.ResponseWriter, r *http.Request, regi
s.writeAccountError(w, err)
return
}
scheme, _ := s.expectedOrigin(r)
http.SetCookie(w, &http.Cookie{Name: s.passkeyCookie(registration), Value: value.Token, Path: "/api/", HttpOnly: true, Secure: scheme == "https", SameSite: http.SameSiteStrictMode, MaxAge: 300})
s.setCookie(w, r, cookie{name: s.passkeyCookie(registration), value: value.Token, path: "/api/", maxAge: 300})
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, json.RawMessage(value.Options))
}
@@ -63,7 +62,7 @@ func (s *Server) handlePasskeyFinish(w http.ResponseWriter, r *http.Request, reg
http.Error(w, "passkey request expired", http.StatusUnauthorized)
return
}
http.SetCookie(w, &http.Cookie{Name: s.passkeyCookie(registration), Path: "/api/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
s.clearCookie(w, r, s.passkeyCookie(registration), "/api/")
var request struct {
Credential json.RawMessage `json:"credential"`
Name string `json:"name"`
@@ -77,7 +76,7 @@ func (s *Server) handlePasskeyFinish(w http.ResponseWriter, r *http.Request, reg
return
}
if !registration {
s.clearProviderCookie(w)
s.clearCookie(w, r, s.cookies().providerToken, "/")
s.setAccountCookie(w, r, value)
}
writeJSON(w, map[string]any{"user": value.Identity})
+7
View File
@@ -243,6 +243,13 @@ type Server struct {
latest map[string]liveUpdate
}
// secureRequest reports whether the browser reached the dashboard over HTTPS,
// directly or through a trusted proxy that terminates TLS.
func (s *Server) secureRequest(r *http.Request) bool {
scheme, _ := s.expectedOrigin(r)
return scheme == "https"
}
func (s *Server) trustForwardedHeaders() bool {
if s == nil {
return false
+1 -1
View File
@@ -48,7 +48,7 @@ func TestUsageNeedsAdminOrOwner(t *testing.T) {
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "https://archie.example/api/usage", nil)
req.Header.Set("X-Archie-CSRF", "1")
req.AddCookie(&http.Cookie{Name: "archie_session", Value: "valid"})
sendCookie(req, "archie_session", "valid")
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != tt.want {
+3 -3
View File
@@ -2,7 +2,7 @@ package worktree
import (
"net/http"
"net/http/cgi"
"net/http/cgi" //nolint:gosec // G504: serves git http-backend; the Httpoxy CVE predates Go 1.6.3.
"net/http/httptest"
"os"
"os/exec"
@@ -87,7 +87,7 @@ func TestForgeHTTPAuthentication(t *testing.T) {
defer target.Close()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if tc.foreign {
http.Redirect(w, r, target.URL+r.URL.RequestURI(), http.StatusTemporaryRedirect)
http.Redirect(w, r, target.URL+r.URL.RequestURI(), http.StatusTemporaryRedirect) //nolint:gosec // G710: the foreign redirect is what the test checks.
return
}
user, password, ok := r.BasicAuth()
@@ -101,7 +101,7 @@ func TestForgeHTTPAuthentication(t *testing.T) {
return
}
if tc.redirect && !strings.HasPrefix(r.URL.Path, "/redirect/") {
http.Redirect(w, r, "/redirect"+r.URL.RequestURI(), http.StatusTemporaryRedirect)
http.Redirect(w, r, "/redirect"+r.URL.RequestURI(), http.StatusTemporaryRedirect) //nolint:gosec // G710: the foreign redirect is what the test checks.
return
}
r.URL.Path = strings.TrimPrefix(r.URL.Path, "/redirect")
+14 -11
View File
@@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"log/slog"
"os"
"path/filepath"
@@ -550,18 +551,20 @@ func cleanUntracked(dir string, tree *object.Tree) error {
if err := collectTrackedPaths(tree, "", files, dirs, opaqueDirs); err != nil {
return err
}
return filepath.WalkDir(dir, func(path string, entry os.DirEntry, walkErr error) error {
// The agent writes this tree, so every operation goes through a root that
// refuses to follow a symlink out of it, even one swapped in mid-walk.
root, err := os.OpenRoot(dir)
if err != nil {
return err
}
defer func() { _ = root.Close() }()
return fs.WalkDir(root.FS(), ".", func(rel string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if path == dir {
if rel == "." {
return nil
}
rel, err := filepath.Rel(dir, path)
if err != nil {
return err
}
rel = filepath.ToSlash(rel)
if rel == ".git" {
// Leave a .git file or directory alone.
if entry.IsDir() {
@@ -580,7 +583,7 @@ func cleanUntracked(dir string, tree *object.Tree) error {
// directory sitting on a path the tree declares as a FILE -- is
// output, not tracked content. It has to go before the reset can
// write the file this path is supposed to hold.
if err := os.RemoveAll(path); err != nil {
if err := root.RemoveAll(rel); err != nil {
return err
}
return filepath.SkipDir
@@ -588,7 +591,7 @@ func cleanUntracked(dir string, tree *object.Tree) error {
if _, ok := files[rel]; ok {
return nil
}
return os.Remove(path)
return root.Remove(rel)
})
}
@@ -634,7 +637,7 @@ func (m *Manager) setIdentity(r *git.Repository) error {
// writeSentinel marks the worktree as fully prepared.
func writeSentinel(dir string) error {
if err := os.WriteFile(filepath.Join(dir, preparedSentinel), nil, 0o644); err != nil {
if err := os.WriteFile(filepath.Join(dir, preparedSentinel), nil, 0o644); err != nil { //nolint:gosec // G306: the task container reads the sentinel as another user.
return fmt.Errorf("write prepared sentinel: %w", err)
}
return nil
@@ -1046,7 +1049,7 @@ func writeSnapshotFile(destDir string, file *object.File) error {
if err != nil {
return fmt.Errorf("read tracked file %s: %w", file.Name, err)
}
if err := os.WriteFile(target, []byte(contents), 0o644); err != nil {
if err := os.WriteFile(target, []byte(contents), 0o644); err != nil { //nolint:gosec // G306: the task container works on these files as another user.
return fmt.Errorf("write snapshot file %s: %w", file.Name, err)
}
return nil