Slice 2 of 4 for runtime experiment rules: persist one rule per experiment in `site_configs`, with revisions that only increase, and add an audit record type. Nothing calls this code yet, so behavior does not change. ## What's in it - **Queries** in `siteconfig.sql`, all checked by dbauthz against `ResourceDeploymentConfig`: - `GetExperimentRules` (read) lists `experiment_rule:` keys with `starts_with`, not `LIKE`, because `_` is a `LIKE` wildcard. - `GetExperimentRule` (read) reads one row. - `UpsertExperimentRule` (update) writes one row. - **`experiments.WriteRule(ctx, db, actor, ex, rule, expectedRevision)`** validates the rule first, then does everything in one `READ COMMITTED` transaction: - It takes an advisory lock for that experiment, waiting at most 5 s. - It reads the current row; a missing row counts as revision 0. - It returns `*RevisionConflictError` when the expected revision is stale. - An identical mode and condition writes nothing and returns `changed=false`. The first `inherit` on a missing row is a change and stores revision 1. - Otherwise it writes `revision+1` with the actor and time, and returns the old and new rule as read and written inside the transaction. - **`experiments.NewDBStore(db)`** implements the evaluator's `Store`. It reads rules by prefix, plus the user's id, username, email, explicit site roles, member org names, and `<org>/<group>` group names (including `<org>/Everyone`). It runs as the system. - **Audit:** - A new `resource_type` enum value `experiment_rule` (migration `000602`; the down migration is a comment because PostgreSQL cannot drop enum values). - A new struct `database.ExperimentRule`. `experiments.AuditRecord` derives its ID from the experiment name, so audit history groups by experiment. - In the audit table, `experiment`, `mode` `revision` and `condition` are tracked (`ActionTrack`), so the audit diff shows the old and new condition. In Enterprise, the slog audit backend also writes that diff to the server log. Admins and auditors can already read the condition through the rules API. - The audit page filter includes the new resource type. ## Testing - `WriteRule` and `NewDBStore` tests run against real PostgreSQL. They cover stale revisions after a reset and a recreate, two concurrent writers with the same expected revision (exactly one wins), no-ops, and rollback after a forced error. - dbauthz method tests and an audit diff test that shows both condition texts. Remote dogfood UAT through Coder Agents passed the upgrade from slice 1 (existing state kept, enum value added), a fresh install, unchanged `/api/v2/experiments`, and the `WriteRule` tests under `-race`. The licensed audit-page check could not run: the test workspace has no premium license. That round tested `015979ca96`. The commit after it only adds `AuditRecord`, and a follow-up UAT round will cover the final head. > [!NOTE] > Migration `000604` was the next free number when this was written. Recheck it before merging. ## Stack 1. #29869: evaluator library 2. **This PR:** storage and audit types 3. Enforcement and discovery (`/api/v2/experiments`, meta tag, chatd `mcp-tool-search`, ruleguard) 4. Control plane (experimental API, `coder exp experiment-rules` CLI, docs) > [!NOTE] > This PR was written by an AI agent (Xum). --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ --------- Signed-off-by: Thomas Kosiewski <tk@coder.com>
91 lines
3.0 KiB
Go
91 lines
3.0 KiB
Go
package experiments
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"slices"
|
|
|
|
"github.com/google/uuid"
|
|
"golang.org/x/xerrors"
|
|
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/database/dbauthz"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
)
|
|
|
|
// NewDBStore returns a Store that reads rules and subject attributes from
|
|
// db. Reads run as the system: the Evaluator decides for any subject, not
|
|
// for the caller.
|
|
func NewDBStore(db database.Store) Store {
|
|
return dbStore{db: db}
|
|
}
|
|
|
|
type dbStore struct {
|
|
db database.Store
|
|
}
|
|
|
|
// Rules implements Store. Rows for unknown experiments are returned keyed
|
|
// by their name, and values are returned undecoded; the Evaluator ignores
|
|
// the former and decides off for undecodable values.
|
|
func (s dbStore) Rules(ctx context.Context) (map[codersdk.Experiment]StoredRule, error) {
|
|
//nolint:gocritic // The Evaluator reads rules for every subject.
|
|
rows, err := s.db.GetExperimentRules(dbauthz.AsSystemRestricted(ctx))
|
|
if err != nil {
|
|
return nil, xerrors.Errorf("get experiment rules: %w", err)
|
|
}
|
|
rules := make(map[codersdk.Experiment]StoredRule, len(rows))
|
|
for _, row := range rows {
|
|
rules[codersdk.Experiment(row.Experiment)] = StoredRule{Value: []byte(row.Value)}
|
|
}
|
|
return rules, nil
|
|
}
|
|
|
|
// UserAttributes implements Store.
|
|
func (s dbStore) UserAttributes(ctx context.Context, userID uuid.UUID) (User, error) {
|
|
//nolint:gocritic // Conditions read the subject's attributes, not the caller's.
|
|
ctx = dbauthz.AsSystemRestricted(ctx)
|
|
user, err := s.db.GetUserByID(ctx, userID)
|
|
if err != nil {
|
|
return User{}, xerrors.Errorf("get user: %w", err)
|
|
}
|
|
orgs, err := s.db.GetOrganizationsByUserID(ctx, database.GetOrganizationsByUserIDParams{
|
|
UserID: userID,
|
|
Deleted: sql.NullBool{Bool: false, Valid: true},
|
|
})
|
|
if err != nil {
|
|
return User{}, xerrors.Errorf("get user organizations: %w", err)
|
|
}
|
|
groups, err := s.db.GetGroups(ctx, database.GetGroupsParams{HasMemberID: userID})
|
|
if err != nil {
|
|
return User{}, xerrors.Errorf("get user groups: %w", err)
|
|
}
|
|
|
|
attrs := User{
|
|
ID: user.ID.String(),
|
|
Username: user.Username,
|
|
Email: user.Email,
|
|
Roles: append([]string{}, user.RBACRoles...),
|
|
Organizations: make([]string, 0, len(orgs)),
|
|
Groups: make([]string, 0, len(groups)),
|
|
}
|
|
activeOrgs := make(map[uuid.UUID]struct{}, len(orgs))
|
|
for _, org := range orgs {
|
|
activeOrgs[org.ID] = struct{}{}
|
|
attrs.Organizations = append(attrs.Organizations, org.Name)
|
|
}
|
|
for _, group := range groups {
|
|
// GetGroups also returns groups of soft-deleted organizations,
|
|
// whose names can be reused by new organizations.
|
|
if _, ok := activeOrgs[group.Group.OrganizationID]; !ok {
|
|
continue
|
|
}
|
|
attrs.Groups = append(attrs.Groups, group.OrganizationName+"/"+group.Group.Name)
|
|
}
|
|
// Queries return rows in no guaranteed order. Sort so that conditions
|
|
// indexing or comparing whole lists decide the same way every time.
|
|
slices.Sort(attrs.Roles)
|
|
slices.Sort(attrs.Organizations)
|
|
slices.Sort(attrs.Groups)
|
|
return attrs, nil
|
|
}
|