Skip to content
Open
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 @@ -6,6 +6,7 @@ All notable changes to this project are documented in this file. The format is b

### Added

- **Global company switcher**: the sidebar header carries a company picker (search, an explicit "all companies", the asset count) that narrows the findings list, the dashboard, the task list, the traffic list and the asset tabs to one target, and persists per browser. Findings with no live asset anchor stay visible under their company. The company now rides on the existing ownership column, so `GET /api/exploration/findings` and `GET /api/traffic` take a `company`/`asset_scope` filter and `GET /api/assets` takes `company_id` on both the plain and the DSL path (#425).
- **Target noise governor**: one shared egress governor paces ARTEX's own HTTP requests (WebFetch, the http custom tools and the enrich probe) against a noise profile (`off` by default, `quiet`, `balanced`, `aggressive`): a per-host token bucket with jitter, per-host and global in-flight caps, 429/503 backoff, GET deduplication with a short cache, and a configurable target User-Agent (`ARTEX_TARGET_USER_AGENT`). Off is a strict passthrough (#205).
- **Low-and-slow prompt block**: when a noise profile is set, the planner, worker, main agent and chat prompts carry the per-host limits of the profile and the exact rate or delay flags for nmap, nuclei, httpx, katana, ffuf, dalfox and sqlmap; with the profile off the prompts are unchanged (#212).
- **Noise profile at runtime**: System settings has a **Target noise** card. It sets the profile (`off`, `quiet`, `balanced`, `aggressive`) through the `noise_profile` setting, which takes precedence over `ARTEX_NOISE_PROFILE`. The change applies to the next WebFetch, http custom tool and enrich request, and to the next agent prompt, without a restart. The card also shows the per-host counters, which `GET /api/settings/noise` returns (#233).
Expand Down
31 changes: 31 additions & 0 deletions db/finding_assets.go
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,37 @@ func (d *DB) applyAssetScope(f FindingFilter) (FindingFilter, error) {
f.assetNone = true
return f, nil
}
// A company scope reads the ownership column directly. The tree holds only
// assets that carry findings plus their ancestors, so an asset reached by a
// finding through a path the tree does not model would be lost.
if id, ok := strings.CutPrefix(scope, "c:"); ok {
var companyID int64
companyID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
f.assetMiss = true
return f, nil
}
// Such findings keep the rows no asset anchors: they belong to no other
// company, so dropping them would hide work from every company view.
f.IncludeUnanchored = true
rows, err := d.Query(`SELECT id FROM assets WHERE company_id = $1`, companyID)
if err != nil {
return f, err
}
defer rows.Close()
for rows.Next() {
var assetID int64
if err := rows.Scan(&assetID); err != nil {
return f, err
}
f.assetIDs = append(f.assetIDs, assetID)
}
if err := rows.Err(); err != nil {
return f, err
}
// No assetMiss on an empty company: it still owns the unanchored findings.
return f, nil
}
// No truncation: dropped endpoints must still take part in id collection,
// otherwise the list would lose rows.
tree, err := d.buildFindingAssetTree(f, 0)
Expand Down
77 changes: 77 additions & 0 deletions db/finding_assets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,3 +242,80 @@ func TestFindingAssetScopeFilter(t *testing.T) {
t.Fatalf("unassigned bucket count: want 2, got %+v", none)
}
}

// TestFindingCompanyScopeFilter pins the company scope semantics: a company
// sees the findings on its own assets plus the ones no asset anchors (they
// belong to no other company), and never another company's. A company with no
// asset yet still shows the unanchored ones instead of an empty page.
func TestFindingCompanyScopeFilter(t *testing.T) {
d, err := Open(testDSN(t))
if err != nil {
SkipPGUnavailable(t, err)
}
defer d.Close()

tk, err := d.CreateTask("company scope filter test", "goal", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer d.DeleteTask(tk.ID)

const root = "company-scope-test.example"
const other = "other-company-scope-test.example"
defer cleanupTreeFixtures(d, tk.ID, root, other)

var mineID, theirsID, emptyID int64
if err := d.QueryRow(`INSERT INTO companies(name, nkey) VALUES ('scope test co', 'scope-test-co') RETURNING id`).Scan(&mineID); err != nil {
t.Fatal(err)
}
if err := d.QueryRow(`INSERT INTO companies(name, nkey) VALUES ('other scope test co', 'other-scope-test-co') RETURNING id`).Scan(&theirsID); err != nil {
t.Fatal(err)
}
if err := d.QueryRow(`INSERT INTO companies(name, nkey) VALUES ('empty scope test co', 'empty-scope-test-co') RETURNING id`).Scan(&emptyID); err != nil {
t.Fatal(err)
}
defer d.Exec(`DELETE FROM companies WHERE id = ANY($1::bigint[])`, []int64{mineID, theirsID, emptyID}) //nolint:errcheck

mineAsset := seedTreeAsset(t, d, "root_domain", map[string]any{"domain": root, "root_domain": root, "company_id": mineID})
theirAsset := seedTreeAsset(t, d, "root_domain", map[string]any{"domain": other, "root_domain": other, "company_id": theirsID})

if _, err := d.AddFinding(tk.ID, 0, "mine", "on my asset", "high", "s", "e", "w", []int64{mineAsset}); err != nil {
t.Fatal(err)
}
if _, err := d.AddFinding(tk.ID, 0, "theirs", "on their asset", "high", "s", "e", "w", []int64{theirAsset}); err != nil {
t.Fatal(err)
}
if _, err := d.AddFinding(tk.ID, 0, "floating", "without an asset", "high", "s", "e", "w", nil); err != nil {
t.Fatal(err)
}

base := FindingFilter{TaskID: strconv.FormatInt(tk.ID, 10)}
cases := []struct {
name string
scope string
want int
}{
{"own asset plus unanchored", companyKey(mineID), 2},
{"other company", companyKey(theirsID), 2},
{"company without assets", companyKey(emptyID), 1},
{"nonexistent company", "c:999000444", 1},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := base
f.AssetScope = tc.scope
items, total, err := d.ListFindingsPage(f, 1, 50)
if err != nil {
t.Fatal(err)
}
if total != tc.want || len(items) != tc.want {
t.Fatalf("scope %s: want %d findings, got total=%d items=%d", tc.scope, tc.want, total, len(items))
}
for _, it := range items {
if tc.scope != companyKey(mineID) && it.Name == "mine" {
t.Fatalf("scope %s leaked the other company's finding", tc.scope)
}
}
})
}
}
64 changes: 56 additions & 8 deletions db/findings.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,9 @@ type FindingFilter struct {
// __none__); selecting a node means selecting its whole subtree.
// Empty = do not filter by asset.
AssetScope string
// IncludeUnanchored keeps findings that carry no live asset in an asset-scoped
// query. Set for company scopes, where such a finding belongs to no other company.
IncludeUnanchored bool

// The three below are resolved from AssetScope by applyAssetScope; callers
// do not set them.
Expand Down Expand Up @@ -249,9 +252,24 @@ func (f FindingFilter) where() (string, []any) {
JOIN assets a ON a.id = e.v::bigint
)
)`)
case len(f.assetIDs) > 0:
args = append(args, assetIDContainments(f.assetIDs))
conds = append(conds, fmt.Sprintf("f.asset_ids @> ANY($%d::jsonb[])", len(args)))
case len(f.assetIDs) > 0 || f.IncludeUnanchored:
cond := "FALSE"
if len(f.assetIDs) > 0 {
args = append(args, assetIDContainments(f.assetIDs))
cond = fmt.Sprintf("f.asset_ids @> ANY($%d::jsonb[])", len(args))
}
if f.IncludeUnanchored {
// A finding with no anchored asset belongs to no other company, so a
// company-wide view keeps it instead of hiding work it cannot attribute.
// FALSE above covers a company that owns no asset at all.
cond = "(" + cond + `
OR jsonb_array_length(COALESCE(f.asset_ids, '[]'::jsonb)) = 0
OR NOT EXISTS (
SELECT 1 FROM jsonb_array_elements_text(f.asset_ids) e(v)
JOIN assets a ON a.id = e.v::bigint
))`
}
conds = append(conds, cond)
}
if query := strings.TrimSpace(f.Query); query != "" {
escaped := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(query)
Expand Down Expand Up @@ -296,11 +314,7 @@ func (d *DB) ListFindingsPage(f FindingFilter, page, pageSize int) ([]*DBFinding
return []*DBFinding{}, total, nil
}

order := "f.created_at DESC, f.id DESC"
if f.Sort == "severity" {
// critical > high > medium > low > others, then newest first.
order = `CASE f.severity WHEN 'critical' THEN 4 WHEN 'high' THEN 3 WHEN 'medium' THEN 2 WHEN 'low' THEN 1 ELSE 0 END DESC, f.created_at DESC, f.id DESC`
}
order := f.orderBy()
pageArgs := append(append([]any{}, args...), pageSize, (page-1)*pageSize)
q := fmt.Sprintf(`
SELECT %s
Expand All @@ -317,6 +331,40 @@ func (d *DB) ListFindingsPage(f FindingFilter, page, pageSize int) ([]*DBFinding
return out, total, err
}

// ListFindingsFiltered returns up to limit findings matching f, newest first,
// without the total count. The dashboard aggregates from it and needs no count.
func (d *DB) ListFindingsFiltered(f FindingFilter, limit int) ([]*DBFinding, error) {
if limit <= 0 {
limit = 500
}
f, err := d.applyAssetScope(f)
if err != nil {
return nil, err
}
where, args := f.where()
q := fmt.Sprintf(`
SELECT %s
FROM findings f
LEFT JOIN tasks t ON f.task_id = t.id%s
ORDER BY %s
LIMIT $%d`, findingSelectCols, where, f.orderBy(), len(args)+1)
rows, err := d.Query(q, append(args, limit)...)
if err != nil {
return nil, err
}
defer rows.Close()
return scanFindings(rows)
}

// orderBy is the list order: severity first when asked, newest first otherwise.
func (f FindingFilter) orderBy() string {
if f.Sort == "severity" {
// critical > high > medium > low > others, then newest first.
return `CASE f.severity WHEN 'critical' THEN 4 WHEN 'high' THEN 3 WHEN 'medium' THEN 2 WHEN 'low' THEN 1 ELSE 0 END DESC, f.created_at DESC, f.id DESC`
}
return "f.created_at DESC, f.id DESC"
}

// FindingGroup is one task-level bucket in the global findings view. TaskID is
// nil for both findings that never had a task and findings retained after task
// deletion; those records intentionally share one "unassigned/deleted" bucket.
Expand Down
34 changes: 34 additions & 0 deletions server/assets.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,33 @@ func (s *Server) companyStore() *db.CompanyStore {
return s.m.pg.Companies()
}

// companyHosts lists the hosts a company owns, for the views that filter on a
// host string instead of an asset id (traffic). Empty for "all companies" and
// for a company that owns no host yet.
func (s *Server) companyHosts(id int64) ([]string, error) {
if id <= 0 || s.m.pg == nil {
return nil, nil
}
rows, err := s.m.pg.Query(`
SELECT DISTINCT COALESCE(NULLIF(domain, ''), NULLIF(ip, ''))
FROM assets
WHERE company_id = $1
AND COALESCE(NULLIF(domain, ''), NULLIF(ip, '')) IS NOT NULL`, id)
if err != nil {
return nil, err
}
defer rows.Close()
out := []string{}
for rows.Next() {
var host string
if err := rows.Scan(&host); err != nil {
return nil, err
}
out = append(out, host)
}
return out, rows.Err()
}

// =====================================================================
// GET /api/companies
// =====================================================================
Expand Down Expand Up @@ -341,6 +368,13 @@ func (s *Server) listAssets(w http.ResponseWriter, r *http.Request) {
// beyond the last row can return an empty page without an expensive scan.
total := 0

// company_id narrows both paths to one company's assets (the sidebar switcher).
if cid, _ := strconv.ParseInt(q.Get("company_id"), 10, 64); cid > 0 {
if dsl := strings.TrimSpace(q.Get("dsl")); dsl != "" {
// No spaces around '=': the DSL lexer takes the operator only tight.
q.Set("dsl", fmt.Sprintf("(company_id=%d) AND (%s)", cid, dsl))
}
}
if dsl := q.Get("dsl"); dsl != "" {
if err := db.ValidateDSL(dsl); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
Expand Down
14 changes: 12 additions & 2 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2214,9 +2214,10 @@ func (s *Server) findings(w http.ResponseWriter, r *http.Request) {
taskParam := q.Get("task")
if taskParam == "" {
// With page/limit → server-side pagination {items,total,...}; without → a bare array (for dashboard aggregation,
// same compat policy as the intents endpoint). Filtering/sorting is pushed down to SQL uniformly.
// same compat policy as the intents endpoint). Filtering/sorting is pushed down to SQL uniformly, and the bare
// array honours the filters too: the dashboard narrows by the active company through asset_scope.
if q.Get("page") == "" && q.Get("limit") == "" {
fs, _ := s.m.pg.ListFindings(500)
fs, _ := s.m.pg.ListFindingsFiltered(findingFilterFromQuery(q), 500)
assets := s.resolveFindingAssets(fs)
out := make([]FindingDTO, 0, len(fs))
for _, f := range fs {
Expand Down Expand Up @@ -3541,7 +3542,16 @@ func (s *Server) getTraffic(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
page := atoiDefault(q.Get("page"), 0)
size := atoiDefault(q.Get("size"), 100)
// company narrows the list to the hosts that company owns, so the page
// follows the sidebar switcher like every other asset-backed view.
hosts, err := s.companyHosts(int64(atoiDefault(q.Get("company"), 0)))
if err != nil {
writeErr(w, 500, err.Error())
return
}
ex, matched, _ := tr.Page(traffic.PageQuery{
MatchNone: q.Get("company") != "" && len(hosts) == 0, // a company owning no host matches nothing
Hosts: hosts,
Host: q.Get("host"),
Method: q.Get("method"),
Query: q.Get("q"),
Expand Down
14 changes: 14 additions & 0 deletions traffic/traffic.go
Original file line number Diff line number Diff line change
Expand Up @@ -1057,6 +1057,8 @@ const (
// newest-first by timestamp.
type PageQuery struct {
Host string // host substring
Hosts []string // exact host allowlist (company scope); empty = no filter
MatchNone bool // force an empty result (a company that owns no host yet)
Method string // exact method (case-insensitive)
Query string // broad search box: metadata columns OR captured text
Body string // content box: captured request/response text only (full-text)
Expand Down Expand Up @@ -1132,6 +1134,18 @@ func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total
if h := strings.TrimSpace(f.Host); h != "" {
add("host LIKE ?", "%"+h+"%")
}
if f.MatchNone {
add("1=0")
}
if len(f.Hosts) > 0 {
placeholders := make([]string, len(f.Hosts))
args2 := make([]any, len(f.Hosts))
for i, h := range f.Hosts {
placeholders[i] = "?"
args2[i] = h
}
add("host IN ("+strings.Join(placeholders, ",")+")", args2...)
}
if m := strings.TrimSpace(f.Method); m != "" {
add("method=?", strings.ToUpper(m))
}
Expand Down
25 changes: 25 additions & 0 deletions traffic/traffic_store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -616,3 +616,28 @@ VALUES(?,?,?,?,?,?,?,?,?,?,?)`, id, ts, host, "GET", "/p/"+id, "https://"+host+"
t.Fatalf("Search rewritten flags = %v", found)
}
}

// TestPageHostsAllowlist pins the company-scope filter: an exact host allowlist
// keeps only those hosts (the substring Host filter stays independent), and
// MatchNone forces an empty result for a company that owns no host.
func TestPageHostsAllowlist(t *testing.T) {
tr, _ := openTraffic(t)
tr.record(newFlow("api.example.com", "GET", "/a", nil, []byte("a")))
tr.record(newFlow("api.other.example", "GET", "/b", nil, []byte("b")))
tr.record(newFlow("shop.example.com", "GET", "/c", nil, []byte("c")))

rows, total, err := tr.Page(PageQuery{Hosts: []string{"api.example.com", "shop.example.com"}, RespMin: -1, RespMax: -1}, 0, 100)
if err != nil || total != 2 || len(rows) != 2 {
t.Fatalf("allowlist should keep 2 rows, got total=%d rows=%d err=%v", total, len(rows), err)
}
// Exact match: api.other.example is not api.example.com.
if rows, _, err := tr.Page(PageQuery{Hosts: []string{"api.example.com"}, RespMin: -1, RespMax: -1}, 0, 100); err != nil || len(rows) != 1 {
t.Fatalf("exact allowlist should keep 1 row, got %d err=%v", len(rows), err)
}
if _, total, err := tr.Page(PageQuery{MatchNone: true, RespMin: -1, RespMax: -1}, 0, 100); err != nil || total != 0 {
t.Fatalf("MatchNone should match nothing, got total=%d err=%v", total, err)
}
if _, total, err := tr.Page(PageQuery{RespMin: -1, RespMax: -1}, 0, 100); err != nil || total != 3 {
t.Fatalf("no filter should return all 3, got %d err=%v", total, err)
}
}
3 changes: 2 additions & 1 deletion web/src/app/(main)/_components/sidebar/app-sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ import { useCurrentUser } from "@/hooks/use-current-user";
import { sidebarItems } from "@/navigation/sidebar/sidebar-items";
import { usePreferencesStore } from "@/stores/preferences/preferences-provider";

import { CompanySwitcher } from "./company-switcher";
import { NavMain } from "./nav-main";
import { NavUser } from "./nav-user";
import { SidebarSupportCard } from "./sidebar-support-card";


export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
const currentUser = useCurrentUser();
const { sidebarVariant, sidebarCollapsible, isSynced } = usePreferencesStore(
Expand Down Expand Up @@ -50,6 +50,7 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
<CompanySwitcher />
</SidebarHeader>
<SidebarContent>
<NavMain items={sidebarItems} />
Expand Down
Loading