feat(shared): add EnsureCoreIndexes

This commit is contained in:
2026-07-24 13:39:46 +01:00
parent 51db5ab2e9
commit b335dc77e3
3 changed files with 94 additions and 3 deletions
+39
View File
@@ -0,0 +1,39 @@
// Package indexes declares the MongoDB indexes more than one Vantage service
// depends on.
package indexes
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
// EnsureCoreIndexes declares the unique indexes on users.email and orgs.slug.
//
// These are a security property, not an optimisation. GetUserByEmail does an
// unscoped FindOne, so a duplicate email would let the OIDC cross-org guard
// compare against an arbitrary user. Every caller must treat a failure here as
// fatal.
//
// Creating an index that already exists with the same specification is a no-op,
// so this is safe to call at every boot from every service.
func EnsureCoreIndexes(ctx context.Context, db *mongo.Database) error {
if _, err := db.Collection("users").Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{{Key: "email", Value: 1}},
Options: options.Index().SetUnique(true),
}); err != nil {
return fmt.Errorf("users.email index: %w", err)
}
if _, err := db.Collection("orgs").Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{{Key: "slug", Value: 1}},
Options: options.Index().SetUnique(true),
}); err != nil {
return fmt.Errorf("orgs.slug index: %w", err)
}
return nil
}