identity: final cuts for H4-M11 (legacy mint, exact remove, guard)
Paul's ruling after review round 3: - mintAccount (moved to accountmint.go) refuses a non-canonical stored owner before any bucket write, so a legacy Sam@ session or CLI token can no longer write a manifest that materialises for sam@; landing, browser and CLI creation all share it. - console member -remove always uses the exact supplied address; the canonical fallback is gone, so repeating a removal cannot reach a lower-case twin. - carlos accounts create returns the owner validation error to the command boundary (rawErr) instead of a new log.Fatalf. - Guard exceptions are per reviewed expression with an exact count; SQL lower()/upper()/COLLATE NOCASE/LIKE on address-like columns is checked again, with two narrow exceptions. - Comments that said Keymail never issues a non-canonical address now name the lowercase-ASCII KEYMAIL_HOST prerequisite.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+738
−475
accounts.go+10 −6cmd/console/member.go+4 −9cmd/console/member_test.go+14 −7internal/console/accountmint.go+67 −0internal/console/demo_claim_auth.go+2 −1internal/console/hunt_H4-M11_test.go+3 −2internal/console/identity.go+9 −1internal/console/identity_foldguard_test.go+548 −0internal/console/identity_guard_test.go+73 −397internal/console/server.go+4 −50internal/console/stepup.go+4 −2
diff --git a/accounts.go b/accounts.go| index 349b0ebbb..a13dc184e 100644 |
| --- a/accounts.go |
| +++ b/accounts.go |
| @@ -96,7 +96,7 @@ func accountsCommand() *clireg.Node { |
| Name: "accounts", |
| Audience: cust, |
| Children: []*clireg.Node{ |
| - raw("create", cust, runAccountsCreate), |
| + rawErr("create", cust, runAccountsCreate), |
| raw("list", cust, runAccountsList), |
| raw("migrate", op, runAccountsMigrate), |
| raw("plan", op, runAccountsPlan), |
| @@ -114,7 +114,10 @@ func accountsCommand() *clireg.Node { |
| } |
| } |
| -func runAccountsCreate(args []string) { |
| +// runAccountsCreate returns the owner's validation error to the command |
| +// boundary (accountsCommand's OnError prints it as "accounts create: <error>" |
| +// and exits 1). |
| +func runAccountsCreate(args []string) error { |
| fs := flag.NewFlagSet("accounts create", flag.ExitOnError) |
| regPath := fs.String("registry", defaultRegistry(), "registry database") |
| name := fs.String("name", "", "account name (a-z, 0-9, hyphen; need not be unique)") |
| @@ -143,8 +146,7 @@ func runAccountsCreate(args []string) { |
| // an account FOR somebody else must not have their own address quietly |
| // substituted. |
| if addr := strings.TrimSpace(*owner); addr != "" { |
| - createAccountInBucket(*regPath, *name, addr) |
| - return |
| + return createAccountInBucket(*regPath, *name, addr) |
| } |
| cred, credErr := loggedInCredential(*console) |
| if credErr != nil { |
| @@ -157,6 +159,7 @@ func runAccountsCreate(args []string) { |
| "(%v)", *name, credErr) |
| } |
| createAccountViaConsole(cred, *regPath, *name) |
| + return nil |
| } |
| // createAccountInBucket is the original path, plus an owner: mint the id with |
| @@ -168,7 +171,7 @@ func runAccountsCreate(args []string) { |
| // cannot land on the same id — and the registry, which only ever materializes |
| // what the bucket says, never has to assign anything. The owner rides along in |
| // that same manifest, which is how the console learns who to admit. |
| -func createAccountInBucket(regPath, name, owner string) { |
| +func createAccountInBucket(regPath, name, owner string) error { |
| // Canonicalise before anything is written OR printed. MintAccount stores |
| // the canonical form, so printing the raw input would tell the operator |
| // their membership is "Paul@Keymail.dev" when the row — and the session |
| @@ -179,7 +182,7 @@ func createAccountInBucket(regPath, name, owner string) { |
| if strings.TrimSpace(owner) != "" { |
| canonical, ok := identity.Canonical(owner) |
| if !ok { |
| - log.Fatalf("accounts create: %q is not a keymail address: expected <user>@<host> in plain ASCII, e.g. paul@keymail.dev", owner) |
| + return fmt.Errorf("%q is not a keymail address: expected <user>@<host> in plain ASCII, e.g. paul@keymail.dev", owner) |
| } |
| owner = canonical |
| } |
| @@ -201,6 +204,7 @@ func createAccountInBucket(regPath, name, owner string) { |
| mutedf(os.Stdout, "use it with: carlos ship --account %s --app <app> ...\n", sqid) |
| fmt.Printf("%s becomes its owner in the console the next time the console materializes\n"+ |
| "accounts from the bucket (on start, or on any `console member` command).\n", owner) |
| + return nil |
| } |
| // createAccountViaConsole mints through the console this terminal is logged in |
diff --git a/cmd/console/member.go b/cmd/console/member.go| index 98761b82a..f288757b0 100644 |
| --- a/cmd/console/member.go |
| +++ b/cmd/console/member.go |
| @@ -97,9 +97,9 @@ func runMember(args []string) { |
| // grant nobody can claim, and a silent typo here is a member who "was |
| // added" and cannot get in. |
| // |
| - // Removal is the exception, below: it acts on the exact stored row |
| - // when there is one, so a legacy Sam@... or non-ASCII row is removed |
| - // as itself and never confused with its lower-case twin. |
| + // Removal is the exception, below: it always acts on the exact |
| + // address supplied, so a legacy Sam@... or non-ASCII row is removed as |
| + // itself, and repeating the command can never reach a lower-case twin. |
| exact = strings.TrimSpace(typed) |
| var canonical bool |
| address, canonical = identity.Canonical(typed) |
| @@ -139,12 +139,7 @@ func runMember(args []string) { |
| case *add: |
| memberAdd(st, acct, address, *role) |
| case *remove: |
| - if role, err := st.Role(acct.ID, exact); err != nil { |
| - log.Fatal(err) |
| - } else if role != "" || address == "" { |
| - address = exact |
| - } |
| - memberRemove(st, acct, address) |
| + memberRemove(st, acct, exact) |
| } |
| } |
diff --git a/cmd/console/member_test.go b/cmd/console/member_test.go| index 6a30c89a6..338cbb887 100644 |
| --- a/cmd/console/member_test.go |
| +++ b/cmd/console/member_test.go |
| @@ -181,12 +181,20 @@ func TestMemberVerbNormalizesTheAddress(t *testing.T) { |
| strings.Contains(out, "JAMES@keymail.dev") { |
| t.Errorf("member list shows an unnormalized address: %s", out) |
| } |
| - // Removal normalizes too, or the tool cannot undo what it just did. |
| + // Removal takes the address exactly as stored (H4-M11): the row the |
| + // verb wrote is james@keymail.dev, so that is the one it removes. A typed |
| + // variant names a different principal and removes nothing. |
| if out, err := run("member", "-remove", "James@Keymail.dev", "bab"); err != nil { |
| + t.Fatalf("member -remove (variant): %v\n%s", err, out) |
| + } |
| + if role := roleOf(t, dbPath, console.OpsAccountID, "james@keymail.dev"); role != console.RoleOwner { |
| + t.Errorf("role after a case-variant removal = %q, want owner untouched", role) |
| + } |
| + if out, err := run("member", "-remove", "james@keymail.dev", "bab"); err != nil { |
| t.Fatalf("member -remove: %v\n%s", err, out) |
| } |
| if role := roleOf(t, dbPath, console.OpsAccountID, "james@keymail.dev"); role != "" { |
| - t.Errorf("role after case-variant removal = %q, want none", role) |
| + t.Errorf("role after removal = %q, want none", role) |
| } |
| } |
| @@ -531,10 +539,9 @@ func TestRevokeActsOnTheExactStoredRow(t *testing.T) { |
| } |
| } |
| -// member -remove takes the exact stored row when there is one, so a legacy |
| -// Sam@ membership is removed as itself and the canonical sam@ is untouched; |
| -// a typed variant of a canonical row still removes it |
| -// (TestMemberVerbNormalizesTheAddress). |
| +// member -remove always takes the exact supplied address, so a legacy Sam@ |
| +// membership is removed as itself, and REPEATING the command (now that Sam@ |
| +// is gone) still never reaches the canonical sam@. |
| func TestMemberRemoveTakesTheExactLegacyRow(t *testing.T) { |
| bin := buildConsole(t) |
| dbPath := filepath.Join(t.TempDir(), "console.db") |
| @@ -552,7 +559,7 @@ func TestMemberRemoveTakesTheExactLegacyRow(t *testing.T) { |
| } |
| } |
| st.Close() |
| - for _, legacy := range []string{"Sam@keymail.dev", "ſue@keymail.dev"} { |
| + for _, legacy := range []string{"Sam@keymail.dev", "ſue@keymail.dev", "Sam@keymail.dev", "ſue@keymail.dev"} { |
| if out, err := run("member", "-remove", legacy, "bab"); err != nil { |
| t.Fatalf("member -remove %s: %v\n%s", legacy, err, out) |
| } |
diff --git a/internal/console/accountmint.go b/internal/console/accountmint.go| new file mode 100644 |
| index 000000000..f789a1113 |
| --- /dev/null |
| +++ b/internal/console/accountmint.go |
| @@ -0,0 +1,67 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "log" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/domains" |
| +) |
| + |
| +// mintAccount creates an account owned by addr: the next free id allocated in |
| +// the bucket, its frozen sqid, and the console DB rows. |
| +// |
| +// The bucket write comes FIRST and is no longer best-effort, because it is now |
| +// the allocator: the id is claimed by a create-only manifest write, which is |
| +// what stops two boxes minting the same integer at the same moment. A console |
| +// row whose manifest never landed would be an account that vanishes on the |
| +// next rebuild — worse than a "new account" button that reports the outage. |
| +// |
| +// The name is NOT validated here: auto-mint names personal accounts by |
| +// keymail address, and landing must never refuse to mint (spec §1). |
| +func (s *Server) mintAccount(ctx context.Context, name, ownerAddr string) (*Account, error) { |
| + // The owner is a STORED principal (a session's or token's address), so it |
| + // is used exactly and never canonicalised (identity.go). A legacy |
| + // non-canonical one (Sam@...) is refused here, before any bucket write: |
| + // otherwise MintAccount would write sam@ into the manifest while the local |
| + // membership said Sam@, and the next materialisation would hand the |
| + // account to the lower-case twin. Past this check the manifest owner and |
| + // the membership are the same exact string. |
| + if !isCanonicalIdentity(ownerAddr) { |
| + return nil, fmt.Errorf("console: %w: %q", errNonCanonicalOwner, ownerAddr) |
| + } |
| + now := time.Now() |
| + id, sqid, err := domains.MintAccount(ctx, s.cfg.Releases, name, ownerAddr, now) |
| + if err != nil { |
| + return nil, err |
| + } |
| + // The default-on analytics setting is written after the manifest and |
| + // before the membership is published, so an account that exists for its |
| + // owner always has it. A failure is handled like a failed CreateAccount |
| + // below: the account is stranded and the caller reports the outage. |
| + if err := s.startNewAccountAnalytics(ctx, sqid); err != nil { |
| + log.Printf("console: minted account %s (id %d, %q) into the bucket but could not turn analytics on: "+ |
| + "%v — accounts/%s/account.json is stranded with no owner", sqid, id, name, err, sqid) |
| + return nil, err |
| + } |
| + if err := s.store.CreateAccount(id, sqid, name, ownerAddr, now); err != nil { |
| + // The manifest already landed, so the id is claimed and there is now an |
| + // account in the bucket with no console row and no owner. It is |
| + // unreachable rather than dangerous (no membership means no access, and |
| + // materialization gives it no members either), and the next mint simply |
| + // takes the id after it. But without this line the only trace is a 500 |
| + // in the user's browser: name the sqid so the stranded account can be |
| + // found and either adopted with `console member -add … -role owner` or |
| + // deleted from the bucket. |
| + log.Printf("console: minted account %s (id %d, %q) into the bucket but could not record it "+ |
| + "locally: %v — accounts/%s/account.json is stranded with no owner", sqid, id, name, err, sqid) |
| + return nil, err |
| + } |
| + if err := s.store.SetLastAccount(ctx, ownerAddr, id); err != nil { |
| + log.Printf("console: set last account for %s: %v", ownerAddr, err) |
| + } |
| + acct := &Account{ID: id, Sqid: sqid, Name: name, Role: RoleOwner, CreatedAt: now} |
| + s.auditAccountCreated(acct, ownerAddr) |
| + return acct, nil |
| +} |
diff --git a/internal/console/demo_claim_auth.go b/internal/console/demo_claim_auth.go| index 346d17b5c..d6d7de1f9 100644 |
| --- a/internal/console/demo_claim_auth.go |
| +++ b/internal/console/demo_claim_auth.go |
| @@ -289,7 +289,8 @@ func (s *Server) proveDemoClaim(ctx context.Context, flow claimFlow, method, add |
| // The proved subject is used exactly as proved (identity.go): a |
| // non-canonical one is refused, never lower-cased into another person. |
| // Email proofs are canonical already (the challenge was made from |
| - // canonicalAddress), and Keymail only issues canonical addresses. |
| + // canonicalAddress), and Keymail's are canonical when its KEYMAIL_HOST |
| + // is lowercase ASCII (a deployment prerequisite). |
| addr := address |
| if !isCanonicalIdentity(addr) || (method != MethodEmail && method != MethodKeymail) { |
| return claimFlow{}, ErrDemoToken |
diff --git a/internal/console/hunt_H4-M11_test.go b/internal/console/hunt_H4-M11_test.go| index 62a4c0f1b..578daba0f 100644 |
| --- a/internal/console/hunt_H4-M11_test.go |
| +++ b/internal/console/hunt_H4-M11_test.go |
| @@ -75,8 +75,9 @@ func TestHunt_H4_M11_StepUpAcceptsFoldEquivalentIdentity(t *testing.T) { |
| // The denial half. The hunt's original pin here asserted that a mixed-case |
| // Keymail sign-in produced a session under the verbatim address. Coordinator |
| // ruling, review round 1: the console's identity contract (identity.go) |
| -// REFUSES a Keymail address that is not already canonical (Keymail itself |
| -// only issues lowercase ASCII), so that premise is now false by design. The |
| +// REFUSES a Keymail address that is not already canonical (Keymail's mailbox |
| +// names are lowercase ASCII, so on a deployment whose KEYMAIL_HOST is |
| +// lowercase ASCII every real address is canonical), so that premise is now false by design. The |
| // pin's security assertion is kept unchanged: a mixed-case Keymail sign-in |
| // never reaches the lower-case user row. Added: it is refused, and leaves no |
| // session and no row of its own. |
diff --git a/internal/console/identity.go b/internal/console/identity.go| index 5d7433626..f6b89a271 100644 |
| --- a/internal/console/identity.go |
| +++ b/internal/console/identity.go |
| @@ -1,6 +1,10 @@ |
| package console |
| -import "github.com/carlosframework/platform/internal/identity" |
| +import ( |
| + "errors" |
| + |
| + "github.com/carlosframework/platform/internal/identity" |
| +) |
| // The console's one identity contract (H4-M11). |
| // |
| @@ -45,6 +49,10 @@ func canonicalIdentity(raw string) (string, bool) { return identity.Canonical(ra |
| // an address that is not; neither ever rewrites it. |
| func isCanonicalIdentity(a string) bool { return identity.IsCanonical(a) } |
| +// errNonCanonicalOwner refuses a mint for a stored principal that is not |
| +// canonical: a legacy session or token from before the contract. |
| +var errNonCanonicalOwner = errors.New("the owner is not a canonical identity") |
| + |
| // identityListed reports whether addr (a principal's canonical address) is on |
| // an operator-configured allowlist. Each entry is canonicalised the same way |
| // the principal's address was; an entry that cannot be canonical matches |
diff --git a/internal/console/identity_foldguard_test.go b/internal/console/identity_foldguard_test.go| new file mode 100644 |
| index 000000000..904117bb0 |
| --- /dev/null |
| +++ b/internal/console/identity_foldguard_test.go |
| @@ -0,0 +1,548 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "fmt" |
| + "go/ast" |
| + "go/parser" |
| + "go/printer" |
| + "go/token" |
| + "path/filepath" |
| + "regexp" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// The guard for the identity contract (internal/identity, H4-M11). |
| +// |
| +// It parses Go source (go/ast, not text) and reports: |
| +// |
| +// - every reference to a case-folding or case-mapping function: strings/ |
| +// bytes EqualFold, ToLower, ToUpper, ToTitle and their Special forms, |
| +// strings.Title, unicode.ToLower/ToUpper/ToTitle/To/SimpleFold (which |
| +// also catches strings.Map(unicode.ToLower, ...)), golang.org/x/text/cases, |
| +// and anything named NormalizeAddress. Import aliases are resolved, a |
| +// call split over lines is one call, and a method value |
| +// (lower := strings.ToLower) is a reference like any other; |
| +// - every string literal in which SQL folds an address-like column: |
| +// lower(...)/upper(...), COLLATE NOCASE or LIKE (case-insensitive for |
| +// ASCII in SQLite) next to address, owner, recipient, email and the like. |
| +// |
| +// The scope is every package that grants or checks an identity: the console, |
| +// cmd/console, account minting (internal/domains and the carlos CLI's |
| +// accounts.go) and the contract itself. |
| +// |
| +// Each hit is keyed by file, enclosing function and the exact expression (or |
| +// SQL line), and identityFoldExceptions lists every reviewed one WITH ITS |
| +// COUNT and the reason it is not an identity decision. A new fold anywhere, |
| +// including a second copy of a reviewed one or a new fold inside a function |
| +// that already has an exception, fails; so does a stale entry. |
| + |
| +// identityGuardScope is what the guard parses, relative to the module root: |
| +// a directory means its non-test .go files, a file means just that file. |
| +var identityGuardScope = []string{ |
| + "internal/console", |
| + "cmd/console", |
| + "internal/domains", |
| + "internal/identity", |
| + "accounts.go", |
| +} |
| + |
| +// foldException is one reviewed fold: how many times exactly that |
| +// expression occurs in that function, and why it is not an identity decision. |
| +type foldException struct { |
| + n int |
| + why string |
| +} |
| + |
| +// foldTargets are the functions the guard reports, by package path. |
| +var foldTargets = map[string]map[string]bool{ |
| + "strings": {"EqualFold": true, "ToLower": true, "ToUpper": true, "ToTitle": true, |
| + "ToLowerSpecial": true, "ToUpperSpecial": true, "ToTitleSpecial": true, "Title": true}, |
| + "bytes": {"EqualFold": true, "ToLower": true, "ToUpper": true, "ToTitle": true, |
| + "ToLowerSpecial": true, "ToUpperSpecial": true, "ToTitleSpecial": true, "Title": true}, |
| + "unicode": {"ToLower": true, "ToUpper": true, "ToTitle": true, "To": true, "SimpleFold": true}, |
| +} |
| + |
| +var ( |
| + // sqlFold is SQL that folds case. LIKE only in capitals, the way this |
| + // codebase writes SQL, so English prose ("looks like") is not SQL. |
| + sqlFold = regexp.MustCompile(`\b(?i:lower|upper)\s*\(|(?i:collate\s+nocase)|\bLIKE\b`) |
| + // sqlIdentityColumn is a column that may hold a person's address. |
| + sqlIdentityColumn = regexp.MustCompile(`\b(address|owner|recipient|email|invited_by|subject|actor|person|operator)\b`) |
| + spaces = regexp.MustCompile(`\s+`) |
| +) |
| + |
| +// findFoldSites reports every fold in one parsed file as "fn: expression" |
| +// keys (one per occurrence). |
| +func findFoldSites(fset *token.FileSet, f *ast.File) []string { |
| + local := map[string]string{} // local import name -> path |
| + var sites []string |
| + for _, imp := range f.Imports { |
| + path, _ := strconv.Unquote(imp.Path.Value) |
| + name := path[strings.LastIndex(path, "/")+1:] |
| + if imp.Name != nil { |
| + name = imp.Name.Name |
| + } |
| + if path == "golang.org/x/text/cases" || (name == "." && foldTargets[path] != nil) { |
| + sites = append(sites, "<imports>: import "+path) |
| + } |
| + local[name] = path |
| + } |
| + text := func(n ast.Node) string { |
| + var b bytes.Buffer |
| + printer.Fprint(&b, fset, n) |
| + return spaces.ReplaceAllString(b.String(), " ") |
| + } |
| + isTarget := func(n ast.Node) bool { |
| + switch x := n.(type) { |
| + case *ast.SelectorExpr: |
| + if id, ok := x.X.(*ast.Ident); ok { |
| + if path, ok := local[id.Name]; ok && foldTargets[path][x.Sel.Name] { |
| + return true |
| + } |
| + } |
| + return x.Sel.Name == "NormalizeAddress" |
| + case *ast.Ident: |
| + return x.Name == "NormalizeAddress" |
| + } |
| + return false |
| + } |
| + inspect := func(fn string, root ast.Node) { |
| + var stack []ast.Node |
| + ast.Inspect(root, func(n ast.Node) bool { |
| + if n == nil { |
| + stack = stack[:len(stack)-1] |
| + return true |
| + } |
| + if lit, ok := n.(*ast.BasicLit); ok && lit.Kind == token.STRING { |
| + if v, err := strconv.Unquote(lit.Value); err == nil { |
| + for _, line := range strings.Split(v, "\n") { |
| + if sqlFold.MatchString(line) && sqlIdentityColumn.MatchString(line) { |
| + sites = append(sites, fn+": sql: "+strings.TrimSpace(spaces.ReplaceAllString(line, " "))) |
| + } |
| + } |
| + } |
| + } |
| + if isTarget(n) { |
| + // A selector inside a selector (x.NormalizeAddress's Ident) is |
| + // the same reference: report the outermost only. |
| + if _, inSel := n.(*ast.Ident); !inSel || len(stack) == 0 || !isTarget(stack[len(stack)-1]) { |
| + expr := n |
| + if len(stack) > 0 { |
| + if call, ok := stack[len(stack)-1].(*ast.CallExpr); ok { |
| + expr = call // the call it is made in, or passed to |
| + } |
| + } |
| + sites = append(sites, fn+": "+text(expr)) |
| + } |
| + } |
| + stack = append(stack, n) |
| + return true |
| + }) |
| + } |
| + for _, d := range f.Decls { |
| + switch d := d.(type) { |
| + case *ast.FuncDecl: |
| + name := d.Name.Name |
| + if d.Recv != nil && len(d.Recv.List) == 1 { |
| + recv := d.Recv.List[0].Type |
| + star := "" |
| + if s, ok := recv.(*ast.StarExpr); ok { |
| + recv, star = s.X, "*" |
| + } |
| + if ix, ok := recv.(*ast.IndexExpr); ok { |
| + recv = ix.X |
| + } |
| + if id, ok := recv.(*ast.Ident); ok { |
| + name = "(" + star + id.Name + ")." + name |
| + } |
| + } |
| + inspect(name, d) |
| + case *ast.GenDecl: |
| + if d.Tok != token.IMPORT { |
| + inspect("<package>", d) |
| + } |
| + } |
| + } |
| + return sites |
| +} |
| + |
| +// foldViolations compares counted sites ("file: fn: expr" -> n) with the |
| +// reviewed exceptions, both ways. |
| +func foldViolations(counted map[string]int, exceptions map[string]foldException) []string { |
| + var out []string |
| + for key, n := range counted { |
| + ex, ok := exceptions[key] |
| + switch { |
| + case !ok: |
| + out = append(out, fmt.Sprintf("unreviewed fold (x%d), outside the identity contract: use identity.Canonical/IsCanonical and ==, or review it into identityFoldExceptions with its count and reason:\n\t%q", n, key)) |
| + case ex.n != n: |
| + out = append(out, fmt.Sprintf("fold count changed: %q occurs %d times, %d reviewed", key, n, ex.n)) |
| + } |
| + } |
| + for key := range exceptions { |
| + if counted[key] == 0 { |
| + out = append(out, fmt.Sprintf("stale identityFoldExceptions entry (the fold is gone; drop it): %q", key)) |
| + } |
| + } |
| + sort.Strings(out) |
| + return out |
| +} |
| + |
| +func TestIdentityFoldGuard(t *testing.T) { |
| + root := filepath.Join("..", "..") |
| + counted := map[string]int{} |
| + for _, scope := range identityGuardScope { |
| + files := []string{filepath.Join(root, scope)} |
| + if !strings.HasSuffix(scope, ".go") { |
| + var err error |
| + if files, err = filepath.Glob(filepath.Join(root, scope, "*.go")); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for _, file := range files { |
| + if strings.HasSuffix(file, "_test.go") { |
| + continue |
| + } |
| + fset := token.NewFileSet() |
| + f, err := parser.ParseFile(fset, file, nil, parser.SkipObjectResolution) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rel, _ := filepath.Rel(root, file) |
| + for _, site := range findFoldSites(fset, f) { |
| + counted[filepath.ToSlash(rel)+": "+site]++ |
| + } |
| + } |
| + } |
| + for _, v := range foldViolations(counted, identityFoldExceptions) { |
| + t.Error(v) |
| + } |
| +} |
| + |
| +// TestIdentityFoldGuardCatchesTheFamily keeps the detector honest on the |
| +// forms a line grep misses, on a new fold inside a function that already has |
| +// an exception, on a second copy of a reviewed fold, and on SQL. |
| +func TestIdentityFoldGuardCatchesTheFamily(t *testing.T) { |
| + src := `package p |
| + |
| +import ( |
| + "bytes" |
| + str "strings" |
| + u "unicode" |
| + |
| + "example.com/domains" |
| +) |
| + |
| +func multiLine(grant struct{ Address string }, addr string) bool { |
| + return str.EqualFold( |
| + grant.Address, |
| + addr, |
| + ) |
| +} |
| + |
| +func methodValue(a string) string { |
| + lower := str.ToLower |
| + return lower(a) |
| +} |
| + |
| +func mapped(address string) string { return str.Map(u.ToLower, address) } |
| + |
| +func bytesFold(a, b []byte) bool { return bytes.EqualFold(a, b) } |
| + |
| +func simple(r rune) rune { return u.SimpleFold(r) } |
| + |
| +func normalised(owner string) string { return domains.NormalizeAddress(owner) } |
| + |
| +type T struct{} |
| + |
| +func (*T) method(a string) string { return str.ToLower(a) } |
| + |
| +var pkgLevel = str.ToLower |
| + |
| +// exempt has a reviewed token-type fold, then grows an address fold and a |
| +// second copy of the reviewed one. |
| +func exempt(tokenType, address string) (bool, string) { |
| + ok := str.EqualFold(tokenType, "bearer") |
| + address = str.ToLower(address) |
| + return ok && str.EqualFold(tokenType, "bearer"), address |
| +} |
| + |
| +const q1 = "SELECT role FROM memberships WHERE lower(address) = ?" |
| +const q2 = ` + "`" + `SELECT 1 FROM invites |
| +WHERE address = ? COLLATE NOCASE` + "`" + ` |
| +const q3 = "SELECT address FROM users WHERE address LIKE ?" |
| +const q4 = "SELECT lower(hex(randomblob(8))) FROM apps" |
| +` |
| + fset := token.NewFileSet() |
| + f, err := parser.ParseFile(fset, "p.go", src, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + counted := map[string]int{} |
| + for _, s := range findFoldSites(fset, f) { |
| + counted["p.go: "+s]++ |
| + } |
| + for _, want := range []string{ |
| + "p.go: multiLine: str.EqualFold( grant.Address, addr, )", |
| + "p.go: methodValue: str.ToLower", |
| + "p.go: mapped: str.Map(u.ToLower, address)", |
| + "p.go: bytesFold: bytes.EqualFold(a, b)", |
| + "p.go: simple: u.SimpleFold(r)", |
| + "p.go: normalised: domains.NormalizeAddress(owner)", |
| + "p.go: (*T).method: str.ToLower(a)", |
| + "p.go: <package>: str.ToLower", |
| + "p.go: exempt: str.ToLower(address)", |
| + "p.go: <package>: sql: SELECT role FROM memberships WHERE lower(address) = ?", |
| + "p.go: <package>: sql: WHERE address = ? COLLATE NOCASE", |
| + "p.go: <package>: sql: SELECT address FROM users WHERE address LIKE ?", |
| + } { |
| + if counted[want] == 0 { |
| + t.Errorf("guard misses %q (found %v)", want, counted) |
| + } |
| + } |
| + if counted["p.go: <package>: sql: SELECT lower(hex(randomblob(8))) FROM apps"] != 0 { |
| + t.Error("guard flags SQL that folds no address-like column") |
| + } |
| + |
| + // The exempt function, reviewed with ONE token-type fold: the new address |
| + // fold and the second copy must both fail. |
| + v := foldViolations(map[string]int{ |
| + "p.go: exempt: str.EqualFold(tokenType, \"bearer\")": counted["p.go: exempt: str.EqualFold(tokenType, \"bearer\")"], |
| + "p.go: exempt: str.ToLower(address)": counted["p.go: exempt: str.ToLower(address)"], |
| + }, map[string]foldException{ |
| + "p.go: exempt: str.EqualFold(tokenType, \"bearer\")": {1, "a token type"}, |
| + }) |
| + joined := strings.Join(v, "\n") |
| + if !strings.Contains(joined, "unreviewed fold") || !strings.Contains(joined, "str.ToLower(address)") { |
| + t.Errorf("a new fold inside an exempt function passed: %v", v) |
| + } |
| + if !strings.Contains(joined, "occurs 2 times, 1 reviewed") { |
| + t.Errorf("a second copy of a reviewed fold passed: %v", v) |
| + } |
| + |
| + dot, err := parser.ParseFile(fset, "d.go", "package p\n\nimport . \"strings\"\n\nvar x = ToLower(\"A\")\n", 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if sites := findFoldSites(fset, dot); len(sites) == 0 { |
| + t.Error("guard misses a dot import of strings") |
| + } |
| +} |
| + |
| +// The reasons, one per kind of non-identity fold. |
| +const ( |
| + whySQLWords = "SQL keywords and identifiers in the claim gate's schema check" |
| + whySVG = "SVG element and attribute names in an uploaded logo check" |
| + whyHost = "a DNS name or host (case-insensitive by RFC 4343); not a person's identity" |
| + whyURL = "a URL path or scheme check" |
| + whySeedMarkerP3 = "a bookkeeping key recording that an operator's alert rules were seeded; grants nothing. P3 follow-up: fold-equivalent legacy addresses share one key and can suppress each other's seeding" |
| + whySearch = "a case-insensitive search filter over rows the viewer can already see; grants nothing" |
| + whyUserCode = "a device-login user code's alphabet normalisation" |
| + whyDigest = "a hex digest, cursor or code shape check; not an identity" |
| + whyConfig = "a region, account sqid or environment value from configuration; not a person" |
| + whyBillingNote = "a word in an operator's billing note" |
| + whyHTTP = "an HTTP header token or media type (case-insensitive by RFC 9110)" |
| + whyCountry = "an ISO country code" |
| + whyCurrency = "an ISO currency code" |
| + whyAccountName = "an account NAME among accounts the caller already holds; membership is checked on the resolved account, and no principal is compared" |
| + whyAppName = "an app or canary name (a lower-case slug); not a person" |
| + whyEnvName = "an environment variable name built from a region code" |
| + whyDisplay = "display text: changes the case of a word in a sentence" |
| + whyMailDomain = "the DOMAIN half of a sender address, matched against verified sending domains (DNS is case-insensitive)" |
| + whyFromAddress = "the console's own configured From address for its outgoing mail; names no principal and grants nothing" |
| + whyAppMailFilter = "a recipient filter over one app's own mail events, after that app's authorisation; grants nothing" |
| + whyOperatorSearch = "the operator-only people search (LIKE is the search, not a match); grants nothing" |
| +) |
| + |
| +// identityFoldExceptions is every reviewed fold: "file: function: expression" |
| +// (or "...: sql: line"), how many times it occurs there, and why it is not an |
| +// identity decision. |
| +var identityFoldExceptions = map[string]foldException{ |
| + "accounts.go: pickAccount: strings.EqualFold(a.Name, want)": {1, whyAccountName}, |
| + "cmd/console/main.go: appRegionsSwitch: strings.EqualFold(strings.TrimSpace(v), \"on\")": {1, whyConfig}, |
| + "cmd/console/main.go: appsDomain: strings.ToLower(strings.TrimSpace(os.Getenv(\"PLATFORM_APPS_DOMAIN\")))": {1, whyHost}, |
| + "cmd/console/main.go: denyDomains: strings.ToLower(strings.TrimSpace(d))": {1, whyHost}, |
| + "cmd/console/main.go: haPoolAccounts: strings.ToLower(strings.TrimSpace(a))": {1, whyConfig}, |
| + "cmd/console/main.go: mailDeployment: strings.ToLower(strings.TrimSpace(os.Getenv(\"CARLOS_MAIL_PLATFORM_SUFFIX\")))": {1, whyHost}, |
| + "cmd/console/main.go: platformDomain: strings.ToLower(strings.TrimSpace(os.Getenv(\"CARLOS_PLATFORM_DOMAIN\")))": {1, whyHost}, |
| + "cmd/console/main.go: relayRegions: strings.ToLower(strings.TrimSpace(r))": {1, whyConfig}, |
| + "cmd/console/main.go: sidecarAccounts: strings.ToLower(strings.TrimSpace(a))": {1, whyConfig}, |
| + "cmd/console/main.go: tunnelHostFrom: strings.ToLower(strings.TrimSpace(getenv(\"CARLOS_TUNNEL_HOST\")))": {1, whyHost}, |
| + "internal/console/accountdomains.go: (*Server).accountDomain: strings.ToLower(strings.TrimSpace(domain))": {1, whyHost}, |
| + "internal/console/accountdomains.go: (*Server).domainCardAddresses: strings.ToLower(c.Host)": {1, whyHost}, |
| + "internal/console/accountdomains.go: (*Server).domainCardAddresses: strings.ToLower(dv.Domain)": {1, whyHost}, |
| + "internal/console/accountdomains.go: (*Server).domainCardRecords: strings.ToLower(purchases[i].Domain)": {1, whyHost}, |
| + "internal/console/accountdomains.go: (*Server).domainCardRecords: strings.ToLower(regs[i].Domain)": {1, whyHost}, |
| + "internal/console/accountdomains.go: (*Server).domainCardsUnread: strings.ToLower(u.Host)": {1, whyHost}, |
| + "internal/console/accountdomains.go: domainCardKey: strings.ToLower(host)": {1, whyHost}, |
| + "internal/console/accountdomainspage.go: domainRegistrable: strings.ToLower(strings.TrimSpace(seg))": {1, whyHost}, |
| + "internal/console/accountplans.go: disabledColumn: strings.ToLower(strings.TrimSpace(h))": {1, whyHost}, |
| + "internal/console/alertdial.go: numericLastLabel: strings.ToLower(last)": {1, whyHost}, |
| + "internal/console/alertdial.go: validConnectorURL: strings.ToLower(host)": {1, whyHost}, |
| + "internal/console/alertengine_pass.go: alertMidSentence: unicode.ToLower(r)": {1, whyDisplay}, |
| + "internal/console/alertnotify.go: (alertTestFailure).Reason: unicode.ToLower(c)": {1, whyDisplay}, |
| + "internal/console/alertpages.go: (*Server).alertDoorForm: strings.ToLower(r.Header.Get(\"Content-Type\"))": {1, whyHTTP}, |
| + "internal/console/alertstore.go: alertSeededMarker: strings.ToLower(strings.TrimSpace(addr))": {1, whySeedMarkerP3}, |
| + "internal/console/analyticsdisplay.go: countryFlag: strings.ToUpper(code)": {1, whyCountry}, |
| + "internal/console/analyticsdisplay.go: countryName: strings.ToUpper(code)": {1, whyCountry}, |
| + "internal/console/apex.go: (*Server).apexHost: strings.ToLower(strings.TrimSpace(s.cfg.AppsDomain))": {1, whyHost}, |
| + "internal/console/apex.go: (*Server).apexSquats: strings.ToLower(strings.TrimSpace(s.cfg.AppsDomain))": {1, whyHost}, |
| + "internal/console/apibilling.go: (*Server).closeUnresolvedOpLocked: strings.ToLower(strings.TrimSpace(note))": {1, whyBillingNote}, |
| + "internal/console/apiconfig.go: configIfVersionMember: strings.EqualFold(name, \"if_version\")": {1, whyHTTP}, |
| + "internal/console/apiconfig.go: readConfigPutBody: strings.ToLower(ct)": {1, whyHTTP}, |
| + "internal/console/apidbforward.go: readDBReadBody: strings.ToLower(ct)": {1, whyHTTP}, |
| + "internal/console/apidemo.go: (*Server).handleDemoPublish: strings.EqualFold(parts[0], \"Bearer\")": {1, whyHTTP}, |
| + "internal/console/apidemo.go: validateDemoConfig: strings.ToLower(cfg.AppsDomain)": {1, whyHost}, |
| + "internal/console/apidemo.go: validateDemoConfig: strings.ToLower(origin.Hostname())": {1, whyHost}, |
| + "internal/console/apidomaincert.go: (*Server).certWildcardCovered: strings.ToLower(strings.TrimSuffix(s.cfg.AppsDomain, \".\"))": {1, whyHost}, |
| + "internal/console/apidomaincert.go: exactSAN: strings.EqualFold(strings.TrimSuffix(n, \".\"), host)": {1, whyHost}, |
| + "internal/console/apidomains.go: (*Server).consoleHosts: strings.ToLower(u.Hostname())": {1, whyHost}, |
| + "internal/console/apidomains.go: (*Server).delegationCNAMEDelegated: strings.EqualFold(strings.TrimSuffix(got, \".\"), strings.TrimSuffix(want, \".\"))": {1, whyHost}, |
| + "internal/console/apidomains.go: (*Server).denyEntries: strings.ToLower(strings.TrimSpace(entry))": {1, whyHost}, |
| + "internal/console/apidomains.go: (*Server).denyEntries: strings.ToLower(strings.TrimSpace(s.cfg.AppsDomain))": {1, whyHost}, |
| + "internal/console/apidomains.go: (*Server).handleAPIDomainAttach: strings.ToLower(strings.TrimSpace(in.Route))": {2, whyHost}, |
| + "internal/console/apidomains.go: (*Server).reservedDomainsWith: strings.ToLower(strings.TrimSpace(s.cfg.AppsDomain))": {1, whyHost}, |
| + "internal/console/apidomains.go: (*Server).resolveAliasRoute: strings.ToLower(strings.TrimSpace(want))": {1, whyHost}, |
| + "internal/console/apimail.go: (*Server).handleAPIEmailDomainEnsure: strings.ToLower(strings.TrimSpace(req.Domain))": {1, whyHost}, |
| + "internal/console/apimail.go: (*Server).handleAPIEmailDomainRemove: strings.ToLower(strings.TrimSpace(r.PathValue(\"domain\")))": {1, whyHost}, |
| + "internal/console/apimail.go: (*Server).handleAPIEmailDomainVerify: strings.ToLower(strings.TrimSpace(r.PathValue(\"domain\")))": {1, whyHost}, |
| + "internal/console/apipdf.go: (*Server).handleAPIPDF: strings.ToLower(name)": {1, whyURL}, |
| + "internal/console/apiplacements.go: (*Server).placementsBindings: strings.ToLower(given)": {1, whyConfig}, |
| + "internal/console/apipolicy.go: (*Server).applyPolicyChange: strings.ToLower(req.Size.Host)": {1, whyHost}, |
| + "internal/console/apipolicy.go: policyAuditDetail: strings.ToLower(req.Size.Host)": {1, whyHost}, |
| + "internal/console/apiservices.go: serviceHandleOf: strings.ToLower(seg)": {1, whyAppName}, |
| + "internal/console/apistoreuploads.go: uploadsOrigin: strings.ToLower(raw)": {1, whyHost}, |
| + "internal/console/apisubmission.go: (*Server).submissionFromRefusal: strings.ToLower(from[strings.LastIndexByte(from, '@')+1:])": {1, whyMailDomain}, |
| + "internal/console/apisubmission.go: (*Server).submissionPreconditions: strings.ToLower(d)": {1, whyMailDomain}, |
| + "internal/console/apisubmission.go: (*Server).submissionPreconditions: strings.ToLower(from[strings.LastIndexByte(from, '@')+1:])": {1, whyMailDomain}, |
| + "internal/console/apisystemupdate.go: (*Server).bootstrapState: strings.EqualFold(got, art.SHA256)": {1, whyDigest}, |
| + "internal/console/appdomains.go: (*Server).handleAppDomainAttach: strings.ToLower(strings.TrimSpace(r.FormValue(\"host\")))": {1, whyHost}, |
| + "internal/console/appdomains.go: (*Server).handleAppDomainDetach: strings.ToLower(strings.TrimSpace(r.FormValue(\"confirm\")))": {1, whyHost}, |
| + "internal/console/appdomains.go: (*Server).handleAppDomainDetach: strings.ToLower(strings.TrimSpace(r.FormValue(\"host\")))": {1, whyHost}, |
| + "internal/console/appframe.go: (*appFrames).clearAccount: strings.EqualFold(sl.name, seg)": {1, whyAccountName}, |
| + "internal/console/applist.go: appFilter: strings.ToLower(strings.TrimSpace(q))": {1, whySearch}, |
| + "internal/console/applist.go: filterApps: strings.ToLower(r.App)": {1, whySearch}, |
| + "internal/console/applist.go: filterApps: strings.ToLower(r.URL)": {1, whySearch}, |
| + "internal/console/appregionset.go: sentenceCase: strings.ToUpper(msg[:1])": {1, whyDisplay}, |
| + "internal/console/appsettings.go: (*Server).settingsDomains: strings.ToLower(c.Host)": {1, whyHost}, |
| + "internal/console/appsettings.go: (*Server).settingsDomains: strings.ToLower(d.Domain)": {1, whyHost}, |
| + "internal/console/archgraph.go: machineFor: strings.EqualFold(r.Name, label)": {1, whyHost}, |
| + "internal/console/authcli.go: bearer: strings.EqualFold(h[:7], \"bearer \")": {1, whyHTTP}, |
| + "internal/console/authcli.go: decodeJSONBody: strings.ToLower(ct)": {1, whyHTTP}, |
| + "internal/console/authstore.go: NormalizeUserCode: strings.ToUpper(strings.TrimSpace(in))": {1, whyUserCode}, |
| + "internal/console/billingpage.go: (*Server).billingBuy: strings.ToUpper(b.Currency)": {1, whyCurrency}, |
| + "internal/console/billingpage.go: (*Server).billingBuy: strings.ToUpper(c)": {1, whyCurrency}, |
| + "internal/console/billingpage.go: (*Server).billingViewFor: strings.ToUpper(b.Currency)": {1, whyCurrency}, |
| + "internal/console/billingpage.go: currencyQuery: strings.ToLower(raw)": {1, whyCurrency}, |
| + "internal/console/billingpayments_store.go: matchPayment: strings.EqualFold(currency, p.Currency)": {1, whyCurrency}, |
| + "internal/console/billingrevenue.go: (*Store).BillingFacts: strings.ToLower(f.Currency)": {1, whyCurrency}, |
| + "internal/console/claim_backends.go: (backendGuard).domainMembers: strings.ToLower(name)": {1, whyHost}, |
| + "internal/console/claim_backends.go: (claimDNSWriter).check: strings.ToLower(r.Name)": {1, whyHost}, |
| + "internal/console/consolemail.go: ConsoleMailFrom: strings.ToLower(strings.TrimSpace(explicit))": {1, whyFromAddress}, |
| + "internal/console/delivery.go: domainOf: strings.ToLower(addr[i+1:])": {1, whyMailDomain}, |
| + "internal/console/demo_domains.go: (*Server).demoDomainReserved: strings.ToLower(host)": {1, whyHost}, |
| + "internal/console/demo_reports.go: demoReportCursor: strings.ToLower(id)": {1, whyDigest}, |
| + "internal/console/demo_serving.go: demoExactHost: strings.ToLower(host)": {1, whyHost}, |
| + "internal/console/dnsds.go: (*Server).lookupDomainNS: strings.ToLower(strings.TrimSpace(r.Host))": {1, whyHost}, |
| + "internal/console/dnsds.go: dsAnswer: strings.EqualFold(a.Name.String(), q.Name.String())": {1, whyHost}, |
| + "internal/console/dnsds.go: dsAnswer: strings.EqualFold(qs[0].Name.String(), q.Name.String())": {1, whyHost}, |
| + "internal/console/domaincatchall.go: (*Server).catchallParentRefused: strings.ToLower(strings.TrimSpace(entry))": {1, whyHost}, |
| + "internal/console/domainpoint.go: normalizePointDomain: strings.ToLower(strings.TrimSpace(domain))": {1, whyHost}, |
| + "internal/console/domainpolicy.go: (*Server).directAppsDomainHost: strings.ToLower(strings.TrimSpace(s.cfg.AppsDomain))": {1, whyHost}, |
| + "internal/console/domainpolicy.go: (*Server).domainHostPolicy: strings.ToLower(strings.TrimSpace(s.cfg.AppsDomain))": {1, whyHost}, |
| + "internal/console/econlistquery.go: pageEconAccounts: strings.ToLower(q.Q)": {1, whySearch}, |
| + "internal/console/econlistquery.go: pageEconAccounts: strings.ToLower(r.Account)": {1, whySearch}, |
| + "internal/console/econlistquery.go: pageEconAccounts: strings.ToLower(r.Name)": {1, whySearch}, |
| + "internal/console/emailsignin.go: (*Server).sameOrigin: strings.EqualFold(got.Host, want.Host)": {1, whyHost}, |
| + "internal/console/geoipfeed.go: (*geoipFeeder).checkMaxMind: strings.ToLower(strings.TrimSpace(strings.SplitN(string(sumBody), \" \", 2)[0]))": {1, whyDigest}, |
| + "internal/console/homelink.go: homeLinkPublicURL: strings.ToLower(l.AppsDomain)": {1, whyHost}, |
| + "internal/console/keymail.go: (*Keymail).ExchangeGrant: strings.EqualFold(out.TokenType, \"bearer\")": {1, whyHTTP}, |
| + "internal/console/keymail.go: (*Keymail).Host: strings.ToLower(u.Hostname())": {1, whyHost}, |
| + "internal/console/listquery.go: healthSlug: strings.ToLower(word)": {1, whyDisplay}, |
| + "internal/console/mailevents.go: (*Store).MailEvents: sql: recipient = ? COLLATE NOCASE": {1, whyAppMailFilter}, |
| + "internal/console/mailpush.go: (*Server).mailPushURL: strings.ToLower(strings.TrimSpace(s.cfg.AppsDomain))": {1, whyHost}, |
| + "internal/console/managedapi.go: readManagedJSON: strings.ToLower(ct)": {1, whyHTTP}, |
| + "internal/console/opbilling.go: buildOpBillingPayments: strings.ToLower(p.SettledCurrency)": {1, whyCurrency}, |
| + "internal/console/opbilling_money.go: accountMoneyRows: strings.ToLower(p.SettledCurrency)": {1, whyCurrency}, |
| + "internal/console/opbilling_money.go: minorText: strings.ToLower(currency)": {1, whyCurrency}, |
| + "internal/console/opbilling_money.go: minorText: strings.ToUpper(c)": {1, whyCurrency}, |
| + "internal/console/opbilling_money.go: moneyByMonth: strings.ToLower(p.SettledCurrency)": {1, whyCurrency}, |
| + "internal/console/opbilling_money.go: paymentRowEUR: strings.ToLower(p.SettledCurrency)": {1, whyCurrency}, |
| + "internal/console/opbilling_money.go: settledEUR: strings.ToLower(currency)": {1, whyCurrency}, |
| + "internal/console/opbilling_overview.go: opBillingNatives: strings.ToLower(p.SettledCurrency)": {1, whyCurrency}, |
| + "internal/console/oplegal.go: legalPublishedText: unicode.ToLower(r)": {1, whyDisplay}, |
| + "internal/console/oplegal.go: svgFuncsOK: strings.ToLower(v)": {1, whySVG}, |
| + "internal/console/oplegal.go: svgLogoOK: strings.ToLower(a.Name.Local)": {1, whySVG}, |
| + "internal/console/oplegal.go: svgLogoOK: strings.ToLower(t.Name.Local)": {1, whySVG}, |
| + "internal/console/opstore.go: <package>: sql: SELECT COUNT(*) FROM users WHERE address LIKE ?1 ESCAPE '\\'": {1, whyOperatorSearch}, |
| + "internal/console/opstore.go: <package>: sql: WHERE ?1 = '' OR address LIKE ?2 ESCAPE '\\'": {1, whyOperatorSearch}, |
| + "internal/console/perfspeed.go: consoleSpeedRoute: strings.ToUpper(pm)": {1, whyURL}, |
| + "internal/console/plancaps.go: (*Server).customDomain: strings.ToLower(strings.TrimSpace(s.cfg.AppsDomain))": {1, whyHost}, |
| + "internal/console/planlapse_inventory.go: (*Server).lapseInventory: strings.ToLower(c.Host)": {1, whyHost}, |
| + "internal/console/planlapse_inventory.go: (*Server).lapseInventory: strings.ToLower(r.Host)": {2, whyHost}, |
| + "internal/console/planlapse_inventory.go: (*Server).lapseUnreadClaims: strings.ToLower(u.Host)": {1, whyHost}, |
| + "internal/console/planlapse_inventory.go: lapseHosts: strings.ToLower(out[i])": {1, whyHost}, |
| + "internal/console/policysize.go: policySizeChecks: strings.ToLower(req.Size.Host)": {1, whyHost}, |
| + "internal/console/relayops.go: (*Server).relayDomain: strings.ToLower(strings.TrimSpace(s.cfg.AppsDomain))": {1, whyHost}, |
| + "internal/console/relayops.go: (*Server).relayDomain: strings.ToLower(strings.TrimSpace(s.cfg.PlatformDomain))": {1, whyHost}, |
| + "internal/console/relayops.go: (*Server).relayRegions: strings.ToLower(strings.TrimSpace(r))": {1, whyConfig}, |
| + "internal/console/relayops.go: (*Server).relayResolveRegions: strings.ToLower(strings.TrimSpace(r))": {1, whyConfig}, |
| + "internal/console/relayops.go: (*Server).relayRotate: strings.ToLower(strings.TrimSpace(region))": {1, whyConfig}, |
| + "internal/console/relayops.go: relayMastersEnv: strings.ToUpper(strings.ReplaceAll(region, \"-\", \"_\"))": {1, whyEnvName}, |
| + "internal/console/resolve.go: matchAccounts: strings.EqualFold(accts[i].Name, seg)": {1, whyAccountName}, |
| + "internal/console/resolve.go: preferredSeg: strings.EqualFold(accts[i].Name, a.Name)": {1, whyAccountName}, |
| + "internal/console/scanhook.go: validCallbackPath: strings.ToLower(p)": {1, whyURL}, |
| + "internal/console/server.go: (*Server).handleNewCanary: strings.ToLower(strings.TrimSpace(r.FormValue(\"name\")))": {1, whyAppName}, |
| + "internal/console/server.go: (*Server).handleRetireCanary: strings.ToLower(strings.TrimSpace(r.FormValue(\"name\")))": {1, whyAppName}, |
| + "internal/console/server.go: normalizeAppName: strings.ToLower(strings.TrimSpace(name))": {1, whyAppName}, |
| + "internal/console/server.go: normalizeDelegationZone: strings.ToLower(strings.TrimSpace(raw))": {1, whyHost}, |
| + "internal/console/server.go: normalizeHost: strings.ToLower(strings.TrimSpace(host))": {1, whyHost}, |
| + "internal/console/server.go: normalizeSteeringHost: strings.ToLower(strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(raw), \".\")))": {1, whyHost}, |
| + "internal/console/sesevents.go: canonicalSigningCertURL: strings.ToLower(u.Host)": {1, whyHost}, |
| + "internal/console/sesevents.go: validSigningCertURL: strings.ToLower(strings.TrimSpace(region))": {1, whyHost}, |
| + "internal/console/sesevents.go: validSigningCertURL: strings.ToLower(u.Hostname())": {1, whyHost}, |
| + "internal/console/shares.go: (*Server).handleAPISystemShareStop: strings.ToLower(strings.TrimSpace(req.Host))": {1, whyHost}, |
| + "internal/console/store_gate.go: claimAppish: strings.ToLower(col)": {1, whySQLWords}, |
| + "internal/console/store_gate.go: claimBlockedLiteral: strings.ToLower(strings.TrimSpace(s))": {1, whySQLWords}, |
| + "internal/console/store_gate.go: claimSQLCensus: strings.EqualFold(o.name, claimSQLReservedName)": {1, whySQLWords}, |
| + "internal/console/store_gate.go: claimSQLCensus: strings.ToUpper(strings.TrimSpace(o.ddl))": {1, whySQLWords}, |
| + "internal/console/store_gate.go: claimTriggerSQL: strings.ToUpper(event)": {1, whySQLWords}, |
| + "internal/console/store_gate.go: inspectClaimSQL: strings.ToLower(id)": {1, whySQLWords}, |
| + "internal/console/store_gate.go: inspectClaimSQL: strings.ToLower(q[i+1 : i+1+j])": {1, whySQLWords}, |
| + "internal/console/store_gate.go: inspectClaimSQL: strings.ToLower(q[i+1:])": {1, whySQLWords}, |
| + "internal/console/store_gate.go: inspectClaimSQL: strings.ToLower(q[i:j])": {1, whySQLWords}, |
| + "internal/console/subdomains.go: (*Server).appsDomain: strings.ToLower(strings.TrimSpace(s.cfg.AppsDomain))": {1, whyHost}, |
| + "internal/console/subdomains.go: (*Server).subdomainInfrastructure: strings.ToLower(strings.TrimSpace(entry))": {1, whyHost}, |
| + "internal/console/svcpage.go: runMintSentence: strings.ToUpper(msg[:1])": {1, whyDisplay}, |
| + "internal/console/teamdoors.go: (*Server).teamInScope: strings.ToLower(strings.TrimSpace(body.Route))": {1, whyHost}, |
| + "internal/console/usageattrib.go: (*Server).newUsageAttribution: strings.ToLower(strings.TrimSuffix(s.cfg.AppsDomain, \".\"))": {1, whyHost}, |
| + "internal/console/usageattrib.go: (*usageAttribution).namespaceOwner: strings.ToLower(host)": {1, whyHost}, |
| + "internal/console/view.go: isApexDomain: strings.ToLower(strings.TrimSuffix(strings.TrimSpace(host), \".\"))": {1, whyHost}, |
| + "internal/domains/claims.go: NormalizeAliasHost: strings.ToLower(raw)": {1, whyHost}, |
| + "internal/domains/claims.go: ParseInstanceCatchallHost: strings.ToLower(raw)": {1, whyHost}, |
| + "internal/domains/freshdns.go: (*FreshResolver).Forget: strings.ToLower(strings.TrimSuffix(host, \".\"))": {1, whyHost}, |
| + "internal/domains/freshdns.go: (*FreshResolver).Retain: strings.ToLower(strings.TrimSuffix(h, \".\"))": {1, whyHost}, |
| + "internal/domains/freshdns.go: (*FreshResolver).Strike: strings.ToLower(strings.TrimSuffix(host, \".\"))": {1, whyHost}, |
| + "internal/domains/freshdns.go: (*FreshResolver).answer: strings.EqualFold(rr.Header.Name.String(), current)": {2, whyHost}, |
| + "internal/domains/freshdns.go: (*FreshResolver).answer: strings.ToLower(c.CNAME.String())": {1, whyHost}, |
| + "internal/domains/freshdns.go: (*FreshResolver).answer: strings.ToLower(current)": {1, whyHost}, |
| + "internal/domains/freshdns.go: (*FreshResolver).answerAAAA: strings.EqualFold(rr.Header.Name.String(), name+\".\")": {1, whyHost}, |
| + "internal/domains/freshdns.go: (*FreshResolver).lookup: strings.ToLower(strings.TrimSuffix(host, \".\"))": {1, whyHost}, |
| + "internal/domains/freshdns.go: (*FreshResolver).query: strings.EqualFold(reply.Questions[0].Name.String(), fqdn)": {1, whyHost}, |
| + "internal/domains/freshdns.go: (*FreshResolver).serverAddrs: strings.ToLower(strings.TrimSuffix(hosts[i], \".\"))": {1, whyHost}, |
| + "internal/domains/freshdns.go: (*FreshResolver).verifyZone: strings.EqualFold(rr.Header.Name.String(), zone+\".\")": {1, whyHost}, |
| + "internal/domains/freshdns.go: noData: strings.EqualFold(rr.Header.Name.String(), zone+\".\")": {1, whyHost}, |
| + "internal/domains/freshdns.go: referralFrom: strings.ToLower(strings.TrimSuffix(ns.NS.String(), \".\"))": {1, whyHost}, |
| + "internal/domains/freshdns.go: referralFrom: strings.ToLower(strings.TrimSuffix(rr.Header.Name.String(), \".\"))": {2, whyHost}, |
| + "internal/domains/freshdns.go: zoneHint: strings.ToLower(strings.TrimSuffix(rr.Header.Name.String(), \".\"))": {1, whyHost}, |
| + "internal/domains/namespace.go: NormalizeSubdomain: strings.ToLower(strings.TrimSpace(raw))": {1, whyHost}, |
| + "internal/domains/reconcile.go: dnsVerdicts: strings.ToLower(strings.TrimSuffix(host, \".\"))": {1, whyHost}, |
| + "internal/domains/reconcile.go: hostCertExpiry: strings.ToLower(host[i+1:])": {1, whyHost}, |
| + "internal/domains/reconcile.go: hostVerdicts: strings.ToLower(cfg.AppsDomain)": {1, whyHost}, |
| + "internal/domains/reconcile.go: hostVerdicts: strings.ToLower(strings.TrimSuffix(host, \".\"))": {1, whyHost}, |
| + "internal/domains/reconcile.go: stampKey: strings.ToLower(strings.TrimSuffix(host, \".\"))": {1, whyHost}, |
| +} |
diff --git a/internal/console/identity_guard_test.go b/internal/console/identity_guard_test.go| index 736ba442a..2004cad5c 100644 |
| --- a/internal/console/identity_guard_test.go |
| +++ b/internal/console/identity_guard_test.go |
| @@ -1,398 +1,12 @@ |
| package console |
| import ( |
| - "go/ast" |
| - "go/parser" |
| - "go/token" |
| "net/http" |
| "net/url" |
| - "path/filepath" |
| - "strconv" |
| - "strings" |
| "testing" |
| "time" |
| ) |
| -// identityFoldExceptions maps "file: function" to why that function's fold is |
| -// not an identity decision. |
| -var identityFoldExceptions = map[string]string{ |
| - "accounts.go: pickAccount": "an account NAME among accounts the caller already holds; membership is checked on the resolved account, and no principal is compared", |
| - "cmd/console/main.go: appRegionsSwitch": "a region, account sqid or environment value from configuration; not a person", |
| - "cmd/console/main.go: appsDomain": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "cmd/console/main.go: denyDomains": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "cmd/console/main.go: haPoolAccounts": "a region, account sqid or environment value from configuration; not a person", |
| - "cmd/console/main.go: mailDeployment": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "cmd/console/main.go: platformDomain": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "cmd/console/main.go: relayRegions": "a region, account sqid or environment value from configuration; not a person", |
| - "cmd/console/main.go: sidecarAccounts": "a region, account sqid or environment value from configuration; not a person", |
| - "cmd/console/main.go: tunnelHostFrom": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/accountdomains.go: (*Server).accountDomain": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/accountdomains.go: (*Server).domainCardAddresses": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/accountdomains.go: (*Server).domainCardRecords": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/accountdomains.go: (*Server).domainCardsUnread": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/accountdomains.go: domainCardKey": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/accountdomainspage.go: domainRegistrable": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/accountplans.go: disabledColumn": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/alertdial.go: numericLastLabel": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/alertdial.go: validConnectorURL": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/alertengine_pass.go: alertMidSentence": "display text: changes the case of a word in a sentence", |
| - "internal/console/alertnotify.go: (alertTestFailure).Reason": "display text: changes the case of a word in a sentence", |
| - "internal/console/alertpages.go: (*Server).alertDoorForm": "an HTTP header token or media type (case-insensitive by RFC 9110)", |
| - "internal/console/alertstore.go: alertSeededMarker": "a bookkeeping key recording that an operator's alert rules were seeded; grants nothing. P3 follow-up: fold-equivalent legacy addresses share one key and can suppress each other's seeding", |
| - "internal/console/analyticsdisplay.go: countryFlag": "an ISO country code", |
| - "internal/console/analyticsdisplay.go: countryName": "an ISO country code", |
| - "internal/console/apex.go: (*Server).apexHost": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apex.go: (*Server).apexSquats": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apibilling.go: (*Server).closeUnresolvedOpLocked": "a word in an operator's billing note", |
| - "internal/console/apiconfig.go: configIfVersionMember": "an HTTP header token or media type (case-insensitive by RFC 9110)", |
| - "internal/console/apiconfig.go: readConfigPutBody": "an HTTP header token or media type (case-insensitive by RFC 9110)", |
| - "internal/console/apidbforward.go: readDBReadBody": "an HTTP header token or media type (case-insensitive by RFC 9110)", |
| - "internal/console/apidemo.go: (*Server).handleDemoPublish": "an HTTP header token or media type (case-insensitive by RFC 9110)", |
| - "internal/console/apidemo.go: validateDemoConfig": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apidomaincert.go: (*Server).certWildcardCovered": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apidomaincert.go: exactSAN": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apidomains.go: (*Server).consoleHosts": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apidomains.go: (*Server).delegationCNAMEDelegated": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apidomains.go: (*Server).denyEntries": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apidomains.go: (*Server).handleAPIDomainAttach": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apidomains.go: (*Server).reservedDomainsWith": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apidomains.go: (*Server).resolveAliasRoute": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apimail.go: (*Server).handleAPIEmailDomainEnsure": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apimail.go: (*Server).handleAPIEmailDomainRemove": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apimail.go: (*Server).handleAPIEmailDomainVerify": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apipdf.go: (*Server).handleAPIPDF": "a URL path or scheme check", |
| - "internal/console/apiplacements.go: (*Server).placementsBindings": "a region, account sqid or environment value from configuration; not a person", |
| - "internal/console/apipolicy.go: (*Server).applyPolicyChange": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apipolicy.go: policyAuditDetail": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apiservices.go: serviceHandleOf": "an app or canary name (a lower-case slug); not a person", |
| - "internal/console/apistoreuploads.go: uploadsOrigin": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/apisubmission.go: (*Server).submissionFromRefusal": "the DOMAIN half of a sender address, matched against verified sending domains (DNS is case-insensitive)", |
| - "internal/console/apisubmission.go: (*Server).submissionPreconditions": "the DOMAIN half of a sender address, matched against verified sending domains (DNS is case-insensitive)", |
| - "internal/console/apisystemupdate.go: (*Server).bootstrapState": "a hex digest, cursor or code shape check; not an identity", |
| - "internal/console/appdomains.go: (*Server).handleAppDomainAttach": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/appdomains.go: (*Server).handleAppDomainDetach": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/appframe.go: (*appFrames).clearAccount": "an account NAME among accounts the caller already holds; membership is checked on the resolved account, and no principal is compared", |
| - "internal/console/applist.go: appFilter": "a case-insensitive search filter over rows the viewer can already see; grants nothing", |
| - "internal/console/applist.go: filterApps": "a case-insensitive search filter over rows the viewer can already see; grants nothing", |
| - "internal/console/appregionset.go: sentenceCase": "display text: changes the case of a word in a sentence", |
| - "internal/console/appsettings.go: (*Server).settingsDomains": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/archgraph.go: machineFor": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/authcli.go: bearer": "an HTTP header token or media type (case-insensitive by RFC 9110)", |
| - "internal/console/authcli.go: decodeJSONBody": "an HTTP header token or media type (case-insensitive by RFC 9110)", |
| - "internal/console/authstore.go: NormalizeUserCode": "a device-login user code's alphabet normalisation", |
| - "internal/console/billingpage.go: (*Server).billingBuy": "an ISO currency code", |
| - "internal/console/billingpage.go: (*Server).billingViewFor": "an ISO currency code", |
| - "internal/console/billingpage.go: currencyQuery": "an ISO currency code", |
| - "internal/console/billingpayments_store.go: matchPayment": "an ISO currency code", |
| - "internal/console/billingrevenue.go: (*Store).BillingFacts": "an ISO currency code", |
| - "internal/console/claim_backends.go: (backendGuard).domainMembers": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/claim_backends.go: (claimDNSWriter).check": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/consolemail.go: ConsoleMailFrom": "the console's own configured From address for its outgoing mail; names no principal and grants nothing", |
| - "internal/console/delivery.go: domainOf": "the DOMAIN half of a sender address, matched against verified sending domains (DNS is case-insensitive)", |
| - "internal/console/demo_domains.go: (*Server).demoDomainReserved": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/demo_reports.go: demoReportCursor": "a hex digest, cursor or code shape check; not an identity", |
| - "internal/console/demo_serving.go: demoExactHost": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/dnsds.go: (*Server).lookupDomainNS": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/dnsds.go: dsAnswer": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/domaincatchall.go: (*Server).catchallParentRefused": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/domainpoint.go: normalizePointDomain": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/domainpolicy.go: (*Server).directAppsDomainHost": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/domainpolicy.go: (*Server).domainHostPolicy": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/econlistquery.go: pageEconAccounts": "a case-insensitive search filter over rows the viewer can already see; grants nothing", |
| - "internal/console/emailsignin.go: (*Server).sameOrigin": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/geoipfeed.go: (*geoipFeeder).checkMaxMind": "a hex digest, cursor or code shape check; not an identity", |
| - "internal/console/homelink.go: homeLinkPublicURL": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/keymail.go: (*Keymail).ExchangeGrant": "an HTTP header token or media type (case-insensitive by RFC 9110)", |
| - "internal/console/keymail.go: (*Keymail).Host": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/listquery.go: healthSlug": "display text: changes the case of a word in a sentence", |
| - "internal/console/mailpush.go: (*Server).mailPushURL": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/managedapi.go: readManagedJSON": "an HTTP header token or media type (case-insensitive by RFC 9110)", |
| - "internal/console/opbilling.go: buildOpBillingPayments": "an ISO currency code", |
| - "internal/console/opbilling_money.go: accountMoneyRows": "an ISO currency code", |
| - "internal/console/opbilling_money.go: minorText": "an ISO currency code", |
| - "internal/console/opbilling_money.go: moneyByMonth": "an ISO currency code", |
| - "internal/console/opbilling_money.go: paymentRowEUR": "an ISO currency code", |
| - "internal/console/opbilling_money.go: settledEUR": "an ISO currency code", |
| - "internal/console/opbilling_overview.go: opBillingNatives": "an ISO currency code", |
| - "internal/console/oplegal.go: legalPublishedText": "display text: changes the case of a word in a sentence", |
| - "internal/console/oplegal.go: svgFuncsOK": "SVG element and attribute names in an uploaded logo check", |
| - "internal/console/oplegal.go: svgLogoOK": "SVG element and attribute names in an uploaded logo check", |
| - "internal/console/perfspeed.go: consoleSpeedRoute": "a URL path or scheme check", |
| - "internal/console/plancaps.go: (*Server).customDomain": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/planlapse_inventory.go: (*Server).lapseInventory": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/planlapse_inventory.go: (*Server).lapseUnreadClaims": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/planlapse_inventory.go: lapseHosts": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/policysize.go: policySizeChecks": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/relayops.go: (*Server).relayDomain": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/relayops.go: (*Server).relayRegions": "a region, account sqid or environment value from configuration; not a person", |
| - "internal/console/relayops.go: (*Server).relayResolveRegions": "a region, account sqid or environment value from configuration; not a person", |
| - "internal/console/relayops.go: (*Server).relayRotate": "a region, account sqid or environment value from configuration; not a person", |
| - "internal/console/relayops.go: relayMastersEnv": "an environment variable name built from a region code", |
| - "internal/console/resolve.go: matchAccounts": "an account NAME among accounts the caller already holds; membership is checked on the resolved account, and no principal is compared", |
| - "internal/console/resolve.go: preferredSeg": "an account NAME among accounts the caller already holds; membership is checked on the resolved account, and no principal is compared", |
| - "internal/console/scanhook.go: validCallbackPath": "a URL path or scheme check", |
| - "internal/console/server.go: (*Server).handleNewCanary": "an app or canary name (a lower-case slug); not a person", |
| - "internal/console/server.go: (*Server).handleRetireCanary": "an app or canary name (a lower-case slug); not a person", |
| - "internal/console/server.go: normalizeAppName": "an app or canary name (a lower-case slug); not a person", |
| - "internal/console/server.go: normalizeDelegationZone": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/server.go: normalizeHost": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/server.go: normalizeSteeringHost": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/sesevents.go: canonicalSigningCertURL": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/sesevents.go: validSigningCertURL": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/shares.go: (*Server).handleAPISystemShareStop": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/store_gate.go: claimAppish": "SQL keywords and identifiers in the claim gate's schema check", |
| - "internal/console/store_gate.go: claimBlockedLiteral": "SQL keywords and identifiers in the claim gate's schema check", |
| - "internal/console/store_gate.go: claimSQLCensus": "SQL keywords and identifiers in the claim gate's schema check", |
| - "internal/console/store_gate.go: claimTriggerSQL": "SQL keywords and identifiers in the claim gate's schema check", |
| - "internal/console/store_gate.go: inspectClaimSQL": "SQL keywords and identifiers in the claim gate's schema check", |
| - "internal/console/subdomains.go: (*Server).appsDomain": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/subdomains.go: (*Server).subdomainInfrastructure": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/svcpage.go: runMintSentence": "display text: changes the case of a word in a sentence", |
| - "internal/console/teamdoors.go: (*Server).teamInScope": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/usageattrib.go: (*Server).newUsageAttribution": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/usageattrib.go: (*usageAttribution).namespaceOwner": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/console/view.go: isApexDomain": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/claims.go: NormalizeAliasHost": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/claims.go: ParseInstanceCatchallHost": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/freshdns.go: (*FreshResolver).Forget": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/freshdns.go: (*FreshResolver).Retain": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/freshdns.go: (*FreshResolver).Strike": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/freshdns.go: (*FreshResolver).answer": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/freshdns.go: (*FreshResolver).answerAAAA": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/freshdns.go: (*FreshResolver).lookup": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/freshdns.go: (*FreshResolver).query": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/freshdns.go: (*FreshResolver).serverAddrs": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/freshdns.go: (*FreshResolver).verifyZone": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/freshdns.go: noData": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/freshdns.go: referralFrom": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/freshdns.go: zoneHint": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/namespace.go: NormalizeSubdomain": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/reconcile.go: dnsVerdicts": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/reconcile.go: hostCertExpiry": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/reconcile.go: hostVerdicts": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| - "internal/domains/reconcile.go: stampKey": "a DNS name or host (case-insensitive by RFC 4343); not a person's identity", |
| -} |
| - |
| -// The guard for the identity contract (internal/identity, H4-M11). |
| -// |
| -// It parses Go source (go/ast, not text) and reports every reference to a |
| -// case-folding or case-mapping function: strings/bytes EqualFold, ToLower, |
| -// ToUpper, ToTitle and their Special forms, strings.Title, unicode.ToLower/ |
| -// ToUpper/ToTitle/To/SimpleFold (which also catches strings.Map(unicode.ToLower, |
| -// ...)), golang.org/x/text/cases, and anything named NormalizeAddress. Import |
| -// aliases are resolved, a call split over several lines is one call, and a |
| -// method value (lower := strings.ToLower) is a reference like any other. |
| -// |
| -// The scope is every package that grants or checks an identity: the console, |
| -// cmd/console, account minting (internal/domains and the carlos CLI's |
| -// accounts.go) and the contract itself. Each hit must sit in a function |
| -// listed in identityFoldExceptions, with the reason that function's fold is |
| -// not an identity decision. An unlisted hit is either an identity site that |
| -// must use identity.Canonical / IsCanonical and == (fix it), or a new |
| -// non-identity use (list it, with the reason). Stale entries fail too. |
| - |
| -// identityGuardScope is what the guard parses, relative to the module root: |
| -// a directory means its non-test .go files, a file means just that file. |
| -var identityGuardScope = []string{ |
| - "internal/console", |
| - "cmd/console", |
| - "internal/domains", |
| - "internal/identity", |
| - "accounts.go", |
| -} |
| - |
| -// foldSite is one reference the guard found. |
| -type foldSite struct { |
| - fn string // enclosing function, "(*Server).name", "name", or "<package>" |
| - what string // e.g. "strings.ToLower" |
| - line int |
| -} |
| - |
| -// foldTargets are the functions the guard reports, by package path. |
| -var foldTargets = map[string]map[string]bool{ |
| - "strings": {"EqualFold": true, "ToLower": true, "ToUpper": true, "ToTitle": true, |
| - "ToLowerSpecial": true, "ToUpperSpecial": true, "ToTitleSpecial": true, "Title": true}, |
| - "bytes": {"EqualFold": true, "ToLower": true, "ToUpper": true, "ToTitle": true, |
| - "ToLowerSpecial": true, "ToUpperSpecial": true, "ToTitleSpecial": true, "Title": true}, |
| - "unicode": {"ToLower": true, "ToUpper": true, "ToTitle": true, "To": true, "SimpleFold": true}, |
| -} |
| - |
| -// findFoldSites reports every fold reference in one parsed file. |
| -func findFoldSites(fset *token.FileSet, f *ast.File) []foldSite { |
| - local := map[string]string{} // local import name -> path |
| - var sites []foldSite |
| - for _, imp := range f.Imports { |
| - path, _ := strconv.Unquote(imp.Path.Value) |
| - name := path[strings.LastIndex(path, "/")+1:] |
| - if imp.Name != nil { |
| - name = imp.Name.Name |
| - } |
| - if path == "golang.org/x/text/cases" || (name == "." && foldTargets[path] != nil) { |
| - sites = append(sites, foldSite{fn: "<imports>", what: "import " + path, line: fset.Position(imp.Pos()).Line}) |
| - } |
| - local[name] = path |
| - } |
| - inspect := func(fn string, n ast.Node) { |
| - ast.Inspect(n, func(n ast.Node) bool { |
| - switch x := n.(type) { |
| - case *ast.SelectorExpr: |
| - if id, ok := x.X.(*ast.Ident); ok { |
| - if path, ok := local[id.Name]; ok && foldTargets[path][x.Sel.Name] { |
| - sites = append(sites, foldSite{fn: fn, what: path + "." + x.Sel.Name, line: fset.Position(x.Pos()).Line}) |
| - } |
| - } |
| - if x.Sel.Name == "NormalizeAddress" { |
| - sites = append(sites, foldSite{fn: fn, what: "NormalizeAddress", line: fset.Position(x.Pos()).Line}) |
| - } |
| - case *ast.Ident: |
| - if x.Name == "NormalizeAddress" { |
| - sites = append(sites, foldSite{fn: fn, what: "NormalizeAddress", line: fset.Position(x.Pos()).Line}) |
| - } |
| - } |
| - return true |
| - }) |
| - } |
| - for _, d := range f.Decls { |
| - switch d := d.(type) { |
| - case *ast.FuncDecl: |
| - name := d.Name.Name |
| - if d.Recv != nil && len(d.Recv.List) == 1 { |
| - recv := d.Recv.List[0].Type |
| - star := "" |
| - if s, ok := recv.(*ast.StarExpr); ok { |
| - recv, star = s.X, "*" |
| - } |
| - if ix, ok := recv.(*ast.IndexExpr); ok { |
| - recv = ix.X |
| - } |
| - if id, ok := recv.(*ast.Ident); ok { |
| - name = "(" + star + id.Name + ")." + name |
| - } |
| - } |
| - inspect(name, d) |
| - case *ast.GenDecl: |
| - if d.Tok != token.IMPORT { |
| - inspect("<package>", d) |
| - } |
| - } |
| - } |
| - return sites |
| -} |
| - |
| -func TestIdentityFoldGuard(t *testing.T) { |
| - root := filepath.Join("..", "..") |
| - counted := map[string]int{} |
| - for _, scope := range identityGuardScope { |
| - files := []string{filepath.Join(root, scope)} |
| - if !strings.HasSuffix(scope, ".go") { |
| - var err error |
| - if files, err = filepath.Glob(filepath.Join(root, scope, "*.go")); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - for _, file := range files { |
| - if strings.HasSuffix(file, "_test.go") { |
| - continue |
| - } |
| - fset := token.NewFileSet() |
| - f, err := parser.ParseFile(fset, file, nil, parser.SkipObjectResolution) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - rel, _ := filepath.Rel(root, file) |
| - rel = filepath.ToSlash(rel) |
| - for _, site := range findFoldSites(fset, f) { |
| - key := rel + ": " + site.fn |
| - counted[key]++ |
| - if _, ok := identityFoldExceptions[key]; !ok { |
| - t.Errorf("%s:%d: %s in %s is outside the identity contract: use identity.Canonical/IsCanonical and ==, or list %q in identityFoldExceptions with the reason it is not an identity decision", |
| - rel, site.line, site.what, site.fn, key) |
| - } |
| - } |
| - } |
| - } |
| - for key := range identityFoldExceptions { |
| - if counted[key] == 0 { |
| - t.Errorf("stale identityFoldExceptions entry %q: that function no longer folds; drop it", key) |
| - } |
| - } |
| -} |
| - |
| -// TestIdentityFoldGuardCatchesTheFamily keeps the detector honest on the |
| -// forms a line grep misses: a call split over lines, an import alias, a |
| -// method value, strings.Map with a unicode case function, and the rest. |
| -func TestIdentityFoldGuardCatchesTheFamily(t *testing.T) { |
| - src := `package p |
| - |
| -import ( |
| - "bytes" |
| - str "strings" |
| - u "unicode" |
| - |
| - "example.com/domains" |
| -) |
| - |
| -func multiLine(grant struct{ Address string }, addr string) bool { |
| - return str.EqualFold( |
| - grant.Address, |
| - addr, |
| - ) |
| -} |
| - |
| -func methodValue(a string) string { |
| - lower := str.ToLower |
| - return lower(a) |
| -} |
| - |
| -func mapped(address string) string { return str.Map(u.ToLower, address) } |
| - |
| -func bytesFold(a, b []byte) bool { return bytes.EqualFold(a, b) } |
| - |
| -func simple(r rune) rune { return u.SimpleFold(r) } |
| - |
| -func upper(a string) string { return str.ToUpper(a) } |
| - |
| -func normalised(owner string) string { return domains.NormalizeAddress(owner) } |
| - |
| -type T struct{} |
| - |
| -func (*T) method(a string) string { return str.ToLower(a) } |
| - |
| -var pkgLevel = str.ToLower |
| -` |
| - fset := token.NewFileSet() |
| - f, err := parser.ParseFile(fset, "p.go", src, 0) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - got := map[string]bool{} |
| - for _, s := range findFoldSites(fset, f) { |
| - got[s.fn+" "+s.what] = true |
| - } |
| - for _, want := range []string{ |
| - "multiLine strings.EqualFold", |
| - "methodValue strings.ToLower", |
| - "mapped unicode.ToLower", |
| - "bytesFold bytes.EqualFold", |
| - "simple unicode.SimpleFold", |
| - "upper strings.ToUpper", |
| - "normalised NormalizeAddress", |
| - "(*T).method strings.ToLower", |
| - "<package> strings.ToLower", |
| - } { |
| - if !got[want] { |
| - t.Errorf("guard misses %q (found %v)", want, got) |
| - } |
| - } |
| - dot, err := parser.ParseFile(fset, "d.go", "package p\n\nimport . \"strings\"\n\nvar x = ToLower(\"A\")\n", 0) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if sites := findFoldSites(fset, dot); len(sites) == 0 { |
| - t.Error("guard misses a dot import of strings") |
| - } |
| -} |
| - |
| func TestCanonicalIdentity(t *testing.T) { |
| for _, tc := range []struct { |
| in, want string |
| @@ -460,17 +74,7 @@ func TestOperatorAllowlistsUseTheContract(t *testing.T) { |
| // that can no longer be produced through the front door. |
| func legacyCLIToken(t *testing.T, fx *consoleFixture, address string) string { |
| t.Helper() |
| - now := time.Now() |
| - raw, err := fx.st.CreateSessionMethod(address, "", MethodKeymail, now) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := fx.st.RecordStepUp(raw, address, now, now); err != nil { |
| - t.Fatal(err) |
| - } |
| - browser := newBrowser(t) |
| - u, _ := url.Parse(fx.ts.URL) |
| - browser.Jar.SetCookies(u, []*http.Cookie{{Name: sessionCookie, Value: raw, Path: "/"}}) |
| + browser, raw := legacyBrowser(t, fx, address) |
| _, start := postJSON(t, fx.ts.URL+"/auth/cli/start", map[string]string{"label": "test@harness"}, "") |
| userCode, deviceCode := str(t, start, "user_code"), str(t, start, "device_code") |
| if code, _, body := postGated(t, fx, browser, fx.ts.URL+"/auth/cli/approve", |
| @@ -551,3 +155,75 @@ func TestRecipientsNeverReachALowerCaseTwin(t *testing.T) { |
| t.Errorf("store notification recipients = %v, want kim@keymail.dev", got) |
| } |
| } |
| + |
| +// legacyBrowser is a browser holding a session for address made directly, as |
| +// one from before the identity contract would be, with fresh presence. |
| +func legacyBrowser(t *testing.T, fx *consoleFixture, address string) (*http.Client, string) { |
| + t.Helper() |
| + now := time.Now() |
| + raw, err := fx.st.CreateSessionMethod(address, "", MethodKeymail, now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.RecordStepUp(raw, address, now, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + browser := newBrowser(t) |
| + u, _ := url.Parse(fx.ts.URL) |
| + browser.Jar.SetCookies(u, []*http.Cookie{{Name: sessionCookie, Value: raw, Path: "/"}}) |
| + return browser, raw |
| +} |
| + |
| +// H4-M11 final cut: a legacy non-canonical session or CLI token cannot mint |
| +// an account through any console door. Nothing reaches the bucket, so no |
| +// manifest can name the lower-case twin, and materialising the bucket into a |
| +// fresh database never makes the twin an owner. |
| +func TestLegacyOwnerCannotMint(t *testing.T) { |
| + const legacy, twin = "Sam@keymail.dev", "sam@keymail.dev" |
| + doors := map[string]func(t *testing.T, fx *consoleFixture){ |
| + "landing": func(t *testing.T, fx *consoleFixture) { |
| + c, _ := legacyBrowser(t, fx, legacy) |
| + get(t, c, fx.ts.URL+"/") |
| + }, |
| + "POST /accounts/new": func(t *testing.T, fx *consoleFixture) { |
| + c, raw := legacyBrowser(t, fx, legacy) |
| + postForm(t, c, fx.ts.URL+"/accounts/new", url.Values{"csrf": {raw}, "name": {"shop"}}) |
| + }, |
| + "POST /auth/cli/accounts": func(t *testing.T, fx *consoleFixture) { |
| + token := legacyCLIToken(t, fx, legacy) |
| + if st, out := postJSON(t, fx.ts.URL+"/auth/cli/accounts", map[string]string{"name": "shop"}, token); st == http.StatusOK { |
| + t.Errorf("legacy CLI token minted an account: %v", out) |
| + } |
| + }, |
| + } |
| + for name, door := range doors { |
| + t.Run(name, func(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + ctx := t.Context() |
| + before, err := fx.rel.List(ctx, "accounts/") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + door(t, fx) |
| + after, err := fx.rel.List(ctx, "accounts/") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(after) != len(before) { |
| + t.Errorf("a legacy owner wrote to the bucket: %v -> %v", before, after) |
| + } |
| + for _, a := range []string{legacy, twin} { |
| + if accts, _ := fx.st.AccountsFor(a); len(accts) != 0 { |
| + t.Errorf("AccountsFor(%s) = %+v, want none", a, accts) |
| + } |
| + } |
| + fresh := openTestStore(t) |
| + if _, err := MaterializeAccounts(ctx, fx.rel, fresh); err != nil { |
| + t.Fatal(err) |
| + } |
| + if accts, _ := fresh.AccountsFor(twin); len(accts) != 0 { |
| + t.Errorf("materialising into a fresh database made the twin an owner: %+v", accts) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index 5d1f30f72..26f9b3f2d 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -3202,53 +3202,6 @@ func (s *Server) memberAccount(ctx context.Context, addr string) (*Account, erro |
| return nil, nil |
| } |
| -// mintAccount creates an account owned by addr: the next free id allocated in |
| -// the bucket, its frozen sqid, and the console DB rows. |
| -// |
| -// The bucket write comes FIRST and is no longer best-effort, because it is now |
| -// the allocator: the id is claimed by a create-only manifest write, which is |
| -// what stops two boxes minting the same integer at the same moment. A console |
| -// row whose manifest never landed would be an account that vanishes on the |
| -// next rebuild — worse than a "new account" button that reports the outage. |
| -// |
| -// The name is NOT validated here: auto-mint names personal accounts by |
| -// keymail address, and landing must never refuse to mint (spec §1). |
| -func (s *Server) mintAccount(ctx context.Context, name, ownerAddr string) (*Account, error) { |
| - now := time.Now() |
| - id, sqid, err := domains.MintAccount(ctx, s.cfg.Releases, name, ownerAddr, now) |
| - if err != nil { |
| - return nil, err |
| - } |
| - // The default-on analytics setting is written after the manifest and |
| - // before the membership is published, so an account that exists for its |
| - // owner always has it. A failure is handled like a failed CreateAccount |
| - // below: the account is stranded and the caller reports the outage. |
| - if err := s.startNewAccountAnalytics(ctx, sqid); err != nil { |
| - log.Printf("console: minted account %s (id %d, %q) into the bucket but could not turn analytics on: "+ |
| - "%v — accounts/%s/account.json is stranded with no owner", sqid, id, name, err, sqid) |
| - return nil, err |
| - } |
| - if err := s.store.CreateAccount(id, sqid, name, ownerAddr, now); err != nil { |
| - // The manifest already landed, so the id is claimed and there is now an |
| - // account in the bucket with no console row and no owner. It is |
| - // unreachable rather than dangerous (no membership means no access, and |
| - // materialization gives it no members either), and the next mint simply |
| - // takes the id after it. But without this line the only trace is a 500 |
| - // in the user's browser: name the sqid so the stranded account can be |
| - // found and either adopted with `console member -add … -role owner` or |
| - // deleted from the bucket. |
| - log.Printf("console: minted account %s (id %d, %q) into the bucket but could not record it "+ |
| - "locally: %v — accounts/%s/account.json is stranded with no owner", sqid, id, name, err, sqid) |
| - return nil, err |
| - } |
| - if err := s.store.SetLastAccount(ctx, ownerAddr, id); err != nil { |
| - log.Printf("console: set last account for %s: %v", ownerAddr, err) |
| - } |
| - acct := &Account{ID: id, Sqid: sqid, Name: name, Role: RoleOwner, CreatedAt: now} |
| - s.auditAccountCreated(acct, ownerAddr) |
| - return acct, nil |
| -} |
| - |
| // account is the gate on every /a/{seg}/… route: a session, and a segment |
| // that resolves — as a sqid OR a name, symmetrically — to an account the |
| // viewer belongs to. Resolution and membership proof are deliberately the |
| @@ -3939,9 +3892,10 @@ func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) { |
| "Keymail did not accept the sign-in. Please start again.") |
| return |
| } |
| - // The identity contract (identity.go): Keymail's own addresses are always |
| - // canonical, so one that is not is refused, never lower-cased into a |
| - // different person's identity. |
| + // The identity contract (identity.go): Keymail's addresses are canonical |
| + // when its KEYMAIL_HOST is lowercase ASCII (a deployment prerequisite), so |
| + // one that is not is refused, never lower-cased into a different person's |
| + // identity. |
| if !isCanonicalIdentity(grant.Address) { |
| log.Printf("console: sign-in refused: Keymail returned a non-canonical address %q", grant.Address) |
| s.renderMessage(w, r, http.StatusForbidden, "Sign-in failed", keymailAddressRefused) |
diff --git a/internal/console/stepup.go b/internal/console/stepup.go| index 30a8b49a0..43e8d92f8 100644 |
| --- a/internal/console/stepup.go |
| +++ b/internal/console/stepup.go |
| @@ -106,8 +106,10 @@ const stepUpUnavailable = "This action needs you to confirm it's really you with |
| // keymailAddressRefused is the sign-in answer when Keymail vouches for an |
| // address that is not in the identity contract's canonical form |
| -// (identity.go). Keymail never issues one, so this is a misconfigured or |
| -// misbehaving identity provider, not a person who typed something wrong. |
| +// (identity.go). Keymail's mailbox names are lowercase ASCII and the rest is |
| +// its KEYMAIL_HOST, so on a deployment meeting that prerequisite (a lowercase |
| +// ASCII KEYMAIL_HOST) this means a misconfigured or misbehaving identity |
| +// provider, not a person who typed something wrong. |
| const keymailAddressRefused = "Keymail vouched for an address in a form this console can't use, so you have not been signed in." |
| // stepUpHoldFailed is the message when the console cannot hold on to the |