| 1 | package operator |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "crypto/sha256" |
| 7 | "database/sql" |
| 8 | "encoding/base64" |
| 9 | "errors" |
| 10 | "math" |
| 11 | |
| 12 | "amadan.net/oficina/home/internal/home/directorydata" |
| 13 | "amadan.net/oficina/home/roster" |
| 14 | family "amadan.net/rastrillo/rastrillo/crypto" |
| 15 | "github.com/go-json-experiment/json/jsontext" |
| 16 | ) |
| 17 | |
| 18 | type InputBase struct { |
| 19 | Version int `json:"version"` |
| 20 | Operation string `json:"operation"` |
| 21 | OperationID string `json:"operation_id"` |
| 22 | } |
| 23 | |
| 24 | func (b InputBase) matches(r Request) bool { |
| 25 | return b.Version == 1 && b.Operation == r.authorization.Action && b.OperationID == r.authorization.OperationID |
| 26 | } |
| 27 | |
| 28 | type InitializeInput struct { |
| 29 | InputBase |
| 30 | ExpectedGeneration *string `json:"expected_generation"` |
| 31 | Generation string `json:"generation"` |
| 32 | Baseline string `json:"baseline_attestation"` |
| 33 | } |
| 34 | type SeedInput struct { |
| 35 | InputBase |
| 36 | Generation string `json:"expected_generation"` |
| 37 | TeamID int64 `json:"team_id"` |
| 38 | TeamSQID string `json:"team_sqid"` |
| 39 | Label string `json:"label"` |
| 40 | Name string `json:"display_name"` |
| 41 | Receipt jsontext.Value `json:"receipt"` |
| 42 | } |
| 43 | type ProvisionInput struct { |
| 44 | InputBase |
| 45 | Generation string `json:"expected_generation"` |
| 46 | TeamSQID string `json:"team_sqid"` |
| 47 | App string `json:"app"` |
| 48 | Consumer string `json:"consumer"` |
| 49 | Audience string `json:"audience"` |
| 50 | Sequence int64 `json:"expected_sequence"` |
| 51 | } |
| 52 | |
| 53 | type Result struct { |
| 54 | Attempt string `json:"attempt_id,omitempty"` |
| 55 | Expires int64 `json:"expires_at,omitempty"` |
| 56 | Version int `json:"version"` |
| 57 | OperationID string `json:"operation_id"` |
| 58 | Outcome string `json:"outcome"` |
| 59 | Generation string `json:"generation,omitempty"` |
| 60 | TeamID int64 `json:"team_id,omitempty"` |
| 61 | TeamSQID string `json:"team_sqid,omitempty"` |
| 62 | Epoch int64 `json:"epoch,omitempty"` |
| 63 | Record jsontext.Value `json:"record,omitempty"` |
| 64 | Bearer string `json:"bearer,omitempty"` |
| 65 | Receipt jsontext.Value `json:"receipt,omitempty"` |
| 66 | Manifest string `json:"credential_manifest_digest,omitempty"` |
| 67 | } |
| 68 | |
| 69 | func resultFor(r Request) Result { |
| 70 | return Result{Version: 1, OperationID: r.authorization.OperationID, Outcome: "committed"} |
| 71 | } |
| 72 | |
| 73 | type Directory struct { |
| 74 | engine *Engine |
| 75 | owner *OwnerVerifier |
| 76 | signer *family.Keypair |
| 77 | keys []roster.Key |
| 78 | names *directorydata.Store |
| 79 | policy directorydata.Config |
| 80 | apps map[string]bool |
| 81 | } |
| 82 | |
| 83 | func NewDirectory(engine *Engine, owner *OwnerVerifier, signer *family.Keypair, keys []roster.Key, policy directorydata.Config) (*Directory, error) { |
| 84 | if engine == nil || engine.verifier.pins.Role != "directory" || owner == nil || owner.directory != engine.verifier.pins.Origin || !signingKey(signer) || len(keys) == 0 || len(keys) > 8 { |
| 85 | return nil, ErrRefused |
| 86 | } |
| 87 | names, e := directorydata.New(engine.db, engine.sealer, policy) |
| 88 | if e != nil { |
| 89 | return nil, ErrRefused |
| 90 | } |
| 91 | seen := map[string]bool{} |
| 92 | for _, k := range [][]byte{engine.verifier.key, owner.key, signer.SignPub()} { |
| 93 | if seen[string(k)] { |
| 94 | return nil, ErrRefused |
| 95 | } |
| 96 | seen[string(k)] = true |
| 97 | } |
| 98 | ids := map[string]bool{} |
| 99 | for _, k := range keys { |
| 100 | p, e := public(k.Public) |
| 101 | if e != nil || !atom(k.ID, 64) || ids[k.ID] || seen[string(p)] { |
| 102 | return nil, ErrRefused |
| 103 | } |
| 104 | ids[k.ID] = true |
| 105 | seen[string(p)] = true |
| 106 | } |
| 107 | d := &Directory{engine, owner, signer, append([]roster.Key(nil), keys...), names, policy, map[string]bool{}} |
| 108 | d.policy.Apps = append([]string(nil), policy.Apps...) |
| 109 | for _, app := range policy.Apps { |
| 110 | d.apps[app] = true |
| 111 | } |
| 112 | return d, nil |
| 113 | } |
| 114 | func atom(s string, max int) bool { |
| 115 | if len(s) == 0 || len(s) > max { |
| 116 | return false |
| 117 | } |
| 118 | for _, c := range s { |
| 119 | if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '-') { |
| 120 | return false |
| 121 | } |
| 122 | } |
| 123 | return true |
| 124 | } |
| 125 | func (d *Directory) Execute(ctx context.Context, raw []byte) ([]byte, error) { |
| 126 | return d.engine.Execute(ctx, raw, func(ctx context.Context, c *sql.Conn, r Request) ([]byte, error) { |
| 127 | switch r.authorization.Action { |
| 128 | case "directory.initialize": |
| 129 | return d.initialize(ctx, c, r) |
| 130 | case "directory.seed-team": |
| 131 | return d.seed(ctx, c, r) |
| 132 | case "directory.provision-consumer": |
| 133 | return d.provision(ctx, c, r) |
| 134 | case "directory.verify-consumer": |
| 135 | return d.verifyConsumer(ctx, c, r) |
| 136 | case "directory.activate-consumer": |
| 137 | return d.activate(ctx, c, r) |
| 138 | default: |
| 139 | return nil, ErrRefused |
| 140 | } |
| 141 | }) |
| 142 | } |
| 143 | func generation(ctx context.Context, c *sql.Conn, expected string) error { |
| 144 | var actual string |
| 145 | if !CanonicalToken(expected) { |
| 146 | return ErrRefused |
| 147 | } |
| 148 | if e := c.QueryRowContext(ctx, "SELECT generation FROM roster_generation WHERE singleton=1").Scan(&actual); e != nil { |
| 149 | return ErrUnavailable |
| 150 | } |
| 151 | if actual != expected { |
| 152 | return ErrRefused |
| 153 | } |
| 154 | return nil |
| 155 | } |
| 156 | func (d *Directory) initialize(ctx context.Context, c *sql.Conn, r Request) ([]byte, error) { |
| 157 | var in InitializeInput |
| 158 | if DecodeInput(r, &in) != nil || !in.matches(r) || !r.authorization.Initial || in.ExpectedGeneration != nil || !CanonicalToken(in.Generation) || in.Baseline != "operator-attests-never-provisioned" { |
| 159 | return nil, ErrRefused |
| 160 | } |
| 161 | for _, table := range []string{"roster_generation", "roster_consumers", "roster_tokens", "roster_operator_receipts"} { |
| 162 | var n int |
| 163 | if c.QueryRowContext(ctx, "SELECT count(*) FROM "+table).Scan(&n) != nil { |
| 164 | return nil, ErrUnavailable |
| 165 | } |
| 166 | if n != 0 { |
| 167 | return nil, ErrRefused |
| 168 | } |
| 169 | } |
| 170 | if _, e := c.ExecContext(ctx, "INSERT INTO roster_generation VALUES(1,?)", in.Generation); e != nil { |
| 171 | return nil, e |
| 172 | } |
| 173 | result := resultFor(r) |
| 174 | result.Generation = in.Generation |
| 175 | raw, e := encode(result) |
| 176 | if e != nil { |
| 177 | return nil, e |
| 178 | } |
| 179 | h := sha256.Sum256(raw) |
| 180 | if _, e = c.ExecContext(ctx, "INSERT INTO roster_operator_receipts VALUES(?,1,'bootstrap',NULL,?,?,?)", r.authorization.OperationID, in.Generation, h[:], d.engine.now().Unix()); e != nil { |
| 181 | return nil, e |
| 182 | } |
| 183 | return raw, nil |
| 184 | } |
| 185 | func nextTeam(ctx context.Context, c *sql.Conn) (int64, string, error) { |
| 186 | var largest, sequence int64 |
| 187 | if c.QueryRowContext(ctx, "SELECT coalesce(max(id),0) FROM teams").Scan(&largest) != nil { |
| 188 | return 0, "", ErrUnavailable |
| 189 | } |
| 190 | e := c.QueryRowContext(ctx, "SELECT seq FROM sqlite_sequence WHERE name='teams'").Scan(&sequence) |
| 191 | if e != nil && !errors.Is(e, sql.ErrNoRows) { |
| 192 | return 0, "", ErrUnavailable |
| 193 | } |
| 194 | if sequence > largest { |
| 195 | largest = sequence |
| 196 | } |
| 197 | if largest < 0 || largest == math.MaxInt64 { |
| 198 | return 0, "", ErrRefused |
| 199 | } |
| 200 | id := largest + 1 |
| 201 | s, e := TeamSQID(id) |
| 202 | return id, s, e |
| 203 | } |
| 204 | func (d *Directory) seed(ctx context.Context, c *sql.Conn, r Request) ([]byte, error) { |
| 205 | return d.seedTeam(ctx, c, r, false) |
| 206 | } |
| 207 | |
| 208 | // seedTeam is directory.seed-team's mutation. addedAt is the operator |
| 209 | // endpoint's wrapping (team-members.md §3 rule 5): over HTTP the first |
| 210 | // owner's membership records the day it began, in the serving schema's |
| 211 | // memberships.added_at. The native command's selected-release schema has no |
| 212 | // such column, so its path writes the original three columns. |
| 213 | func (d *Directory) seedTeam(ctx context.Context, c *sql.Conn, r Request, addedAt bool) ([]byte, error) { |
| 214 | return d.seedTeamForWindow(ctx, c, r, addedAt, "") |
| 215 | } |
| 216 | |
| 217 | func (d *Directory) seedTeamForWindow(ctx context.Context, c *sql.Conn, r Request, addedAt bool, existingTeam string) ([]byte, error) { |
| 218 | var in SeedInput |
| 219 | if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial || !validTeam(in.TeamID, in.TeamSQID) { |
| 220 | return nil, ErrRefused |
| 221 | } |
| 222 | if (in.Label == "oficina") != (existingTeam != "") || (existingTeam != "" && in.TeamSQID != existingTeam) { |
| 223 | return nil, ErrRefused |
| 224 | } |
| 225 | if e := generation(ctx, c, in.Generation); e != nil { |
| 226 | return nil, e |
| 227 | } |
| 228 | owner, e := d.owner.Verify(in.Receipt, d.engine.now()) |
| 229 | if e != nil || owner.TeamID != in.TeamID || owner.TeamSQID != in.TeamSQID { |
| 230 | return nil, ErrRefused |
| 231 | } |
| 232 | var used int |
| 233 | e = c.QueryRowContext(ctx, "SELECT 1 FROM directory_operator_owner_receipts WHERE issuer=? AND owner_operation_id=?", owner.Issuer, owner.OperationID).Scan(&used) |
| 234 | if e == nil { |
| 235 | return nil, ErrRefused |
| 236 | } |
| 237 | if !errors.Is(e, sql.ErrNoRows) { |
| 238 | return nil, ErrUnavailable |
| 239 | } |
| 240 | id, sqid, e := nextTeam(ctx, c) |
| 241 | if e != nil { |
| 242 | return nil, e |
| 243 | } |
| 244 | if id != in.TeamID || sqid != in.TeamSQID { |
| 245 | return nil, ErrRefused |
| 246 | } |
| 247 | // The unique label belongs to the team across all sibling applications. |
| 248 | if !directorydata.ValidLabel(in.Label) || len(in.Name) > 255 { |
| 249 | return nil, ErrRefused |
| 250 | } |
| 251 | name, e := d.names.SealTeamName(id, in.Name) |
| 252 | if e != nil { |
| 253 | return nil, ErrRefused |
| 254 | } |
| 255 | var collision int |
| 256 | e = c.QueryRowContext(ctx, "SELECT 1 FROM teams WHERE label=? OR sqid=?", in.Label, in.TeamSQID).Scan(&collision) |
| 257 | if e == nil { |
| 258 | return nil, ErrRefused |
| 259 | } |
| 260 | if !errors.Is(e, sql.ErrNoRows) { |
| 261 | return nil, ErrUnavailable |
| 262 | } |
| 263 | res, e := c.ExecContext(ctx, "INSERT INTO teams(sqid,label,sealed_name,created_at) VALUES(?,?,?,?)", sqid, in.Label, name, d.engine.now().Unix()) |
| 264 | if e != nil { |
| 265 | return nil, e |
| 266 | } |
| 267 | inserted, e := res.LastInsertId() |
| 268 | if e != nil || inserted != id { |
| 269 | return nil, ErrUnavailable |
| 270 | } |
| 271 | if addedAt { |
| 272 | _, e = c.ExecContext(ctx, "INSERT INTO memberships(team_id,person_ref,role,added_at) VALUES(?,?,'owner',?)", id, owner.PersonRef, directorydata.MembershipDay(d.engine.now())) |
| 273 | } else { |
| 274 | _, e = c.ExecContext(ctx, "INSERT INTO memberships(team_id,person_ref,role) VALUES(?,?,'owner')", id, owner.PersonRef) |
| 275 | } |
| 276 | if e != nil { |
| 277 | return nil, e |
| 278 | } |
| 279 | if _, e = c.ExecContext(ctx, "INSERT INTO directory_operator_owner_receipts VALUES(?,?,?,?)", owner.Issuer, owner.OperationID, r.authorization.OperationID, id); e != nil { |
| 280 | return nil, e |
| 281 | } |
| 282 | result := resultFor(r) |
| 283 | result.Generation = in.Generation |
| 284 | result.TeamID = id |
| 285 | result.TeamSQID = sqid |
| 286 | if c.QueryRowContext(ctx, "SELECT roster_epoch FROM teams WHERE id=?", id).Scan(&result.Epoch) != nil { |
| 287 | return nil, ErrUnavailable |
| 288 | } |
| 289 | return encode(result) |
| 290 | } |
| 291 | func (d *Directory) provision(ctx context.Context, c *sql.Conn, r Request) ([]byte, error) { |
| 292 | return d.provisionForWindow(ctx, c, r, "") |
| 293 | } |
| 294 | |
| 295 | func (d *Directory) provisionForWindow(ctx context.Context, c *sql.Conn, r Request, existingTeam string) ([]byte, error) { |
| 296 | var in ProvisionInput |
| 297 | if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial || in.Sequence != 0 || !d.apps[in.App] || !atom(in.Consumer, 64) || !Origin(in.Audience) { |
| 298 | return nil, ErrRefused |
| 299 | } |
| 300 | if e := generation(ctx, c, in.Generation); e != nil { |
| 301 | return nil, e |
| 302 | } |
| 303 | route := directorydata.Route{TeamSQID: in.TeamSQID, App: in.App, Origin: in.Audience, ConsumerID: in.Consumer} |
| 304 | var epoch int64 |
| 305 | if e := c.QueryRowContext(ctx, "SELECT id,label,roster_epoch FROM teams WHERE sqid=?", in.TeamSQID).Scan(&route.TeamID, &route.Label, &epoch); e != nil { |
| 306 | if errors.Is(e, sql.ErrNoRows) { |
| 307 | return nil, ErrRefused |
| 308 | } |
| 309 | return nil, ErrUnavailable |
| 310 | } |
| 311 | if !validTeam(route.TeamID, route.TeamSQID) || !d.policy.ValidateRoute(route) || epoch <= 0 { |
| 312 | return nil, ErrRefused |
| 313 | } |
| 314 | if !routeScope(existingTeam, route.Label, in.TeamSQID, in.App, in.Consumer, in.Audience) { |
| 315 | return nil, ErrRefused |
| 316 | } |
| 317 | var owner string |
| 318 | if e := c.QueryRowContext(ctx, "SELECT person_ref FROM memberships WHERE team_id=? AND role='owner' LIMIT 1", route.TeamID).Scan(&owner); e != nil || !PersonRef(owner) { |
| 319 | return nil, ErrRefused |
| 320 | } |
| 321 | var conflict int |
| 322 | e := c.QueryRowContext(ctx, "SELECT 1 FROM team_instances WHERE (team_id=? AND app=?) OR consumer_id=? OR origin=?", route.TeamID, in.App, in.Consumer, in.Audience).Scan(&conflict) |
| 323 | if e == nil { |
| 324 | return nil, ErrRefused |
| 325 | } |
| 326 | if !errors.Is(e, sql.ErrNoRows) { |
| 327 | return nil, ErrUnavailable |
| 328 | } |
| 329 | random := make([]byte, 32) |
| 330 | if _, e = rand.Read(random); e != nil { |
| 331 | return nil, ErrUnavailable |
| 332 | } |
| 333 | token := base64.RawURLEncoding.EncodeToString(random) |
| 334 | hash := sha256.Sum256([]byte(token)) |
| 335 | binding := roster.Bindings{Issuer: d.owner.issuer, Directory: d.owner.directory, Consumer: in.Consumer, App: in.App, Team: in.TeamSQID, Audience: in.Audience} |
| 336 | p := roster.Provisioning{Version: 1, Operation: r.authorization.OperationID, Sequence: 1, Bindings: binding, Generation: in.Generation, MinEpoch: epoch, Keys: d.keys} |
| 337 | record, e := roster.SignProvisioning(d.signer, keyID(d.signer.SignPub()), p) |
| 338 | if e != nil { |
| 339 | return nil, ErrUnavailable |
| 340 | } |
| 341 | if _, e = roster.VerifyProvisioning(record, []roster.Key{{ID: keyID(d.signer.SignPub()), Public: base64.RawURLEncoding.EncodeToString(d.signer.SignPub())}}, binding); e != nil { |
| 342 | return nil, ErrUnavailable |
| 343 | } |
| 344 | if _, e = c.ExecContext(ctx, "INSERT INTO team_instances VALUES(?,?,?,?,'pending')", route.TeamID, in.App, in.Audience, in.Consumer); e != nil { |
| 345 | return nil, e |
| 346 | } |
| 347 | if _, e = c.ExecContext(ctx, "INSERT INTO roster_consumers VALUES(?,?,?,?,1)", in.Consumer, route.TeamID, in.App, in.Audience); e != nil { |
| 348 | return nil, e |
| 349 | } |
| 350 | if _, e = c.ExecContext(ctx, "INSERT INTO roster_tokens VALUES(?,?,'current',?,NULL)", hash[:], in.Consumer, d.engine.now().Unix()); e != nil { |
| 351 | return nil, e |
| 352 | } |
| 353 | recordHash := sha256.Sum256(record) |
| 354 | if _, e = c.ExecContext(ctx, "INSERT INTO roster_operator_receipts VALUES(?,1,'provision',?,?,?,?)", r.authorization.OperationID, in.Consumer, in.Generation, recordHash[:], d.engine.now().Unix()); e != nil { |
| 355 | return nil, e |
| 356 | } |
| 357 | if _, e = c.ExecContext(ctx, "INSERT INTO directory_operator_consumer_records VALUES(?,?,?,?,?)", in.Consumer, r.authorization.OperationID, int64(1), in.Generation, recordHash[:]); e != nil { |
| 358 | return nil, e |
| 359 | } |
| 360 | result := resultFor(r) |
| 361 | result.Generation = in.Generation |
| 362 | result.TeamID = route.TeamID |
| 363 | result.TeamSQID = in.TeamSQID |
| 364 | result.Epoch = epoch |
| 365 | result.Record = record |
| 366 | result.Bearer = token |
| 367 | return encode(result) |
| 368 | } |
| 369 | |