Skip to main content

mz_catalog/durable/
initialize.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::collections::BTreeMap;
11use std::iter;
12use std::str::FromStr;
13use std::sync::LazyLock;
14use std::time::Duration;
15
16use base64::prelude::*;
17use ipnet::IpNet;
18use itertools::max;
19use mz_audit_log::{CreateOrDropClusterReplicaReasonV1, EventV1, VersionedEvent};
20use mz_controller::clusters::ReplicaLogging;
21use mz_controller_types::{ClusterId, ReplicaId};
22use mz_ore::collections::HashSet;
23use mz_ore::now::EpochMillis;
24use mz_persist_types::ShardId;
25use mz_pgrepr::oid::{
26    FIRST_USER_OID, NETWORK_POLICIES_DEFAULT_POLICY_OID, ROLE_PUBLIC_OID,
27    SCHEMA_INFORMATION_SCHEMA_OID, SCHEMA_MZ_CATALOG_OID, SCHEMA_MZ_CATALOG_UNSTABLE_OID,
28    SCHEMA_MZ_INTERNAL_OID, SCHEMA_MZ_INTROSPECTION_OID, SCHEMA_MZ_UNSAFE_OID,
29    SCHEMA_PG_CATALOG_OID,
30};
31use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem};
32use mz_repr::network_policy_id::NetworkPolicyId;
33use mz_repr::role_id::RoleId;
34use mz_sql::catalog::{
35    DefaultPrivilegeAclItem, DefaultPrivilegeObject, ObjectType, RoleAttributesRaw, RoleMembership,
36    RoleVars, SystemObjectType,
37};
38use mz_sql::names::{
39    DatabaseId, ObjectId, PUBLIC_ROLE_NAME, ResolvedDatabaseSpecifier, SchemaId, SchemaSpecifier,
40};
41use mz_sql::plan::{NetworkPolicyRule, PolicyAddress};
42use mz_sql::rbac;
43use mz_sql::session::user::{MZ_SUPPORT_ROLE_ID, MZ_SYSTEM_ROLE_ID};
44
45use crate::builtin::BUILTIN_ROLES;
46use crate::durable::upgrade::CATALOG_VERSION;
47use crate::durable::{
48    AUDIT_LOG_ID_ALLOC_KEY, BUILTIN_MIGRATION_SHARD_KEY, BootstrapArgs,
49    CATALOG_CONTENT_VERSION_KEY, CatalogError, ClusterConfig, ClusterVariant,
50    ClusterVariantManaged, DATABASE_ID_ALLOC_KEY, DefaultPrivilege, EXPRESSION_CACHE_SHARD_KEY,
51    MOCK_AUTHENTICATION_NONCE_KEY, OID_ALLOC_KEY, ReplicaConfig, ReplicaLocation, Role,
52    SCHEMA_ID_ALLOC_KEY, STORAGE_USAGE_ID_ALLOC_KEY, SYSTEM_CLUSTER_ID_ALLOC_KEY,
53    SYSTEM_CLUSTER_REPLICA_SIZE_ID_ALLOC_KEY, SYSTEM_REPLICA_ID_ALLOC_KEY, Schema, Transaction,
54    USER_CLUSTER_ID_ALLOC_KEY, USER_CLUSTER_REPLICA_SIZE_ID_ALLOC_KEY,
55    USER_NETWORK_POLICY_ID_ALLOC_KEY, USER_QUERY_POLICY_ID_ALLOC_KEY, USER_REPLICA_ID_ALLOC_KEY,
56    USER_ROLE_ID_ALLOC_KEY,
57};
58
59/// The key within the "config" Collection that stores the version of the catalog.
60pub const USER_VERSION_KEY: &str = "user_version";
61/// The key within the "config" collection that stores whether the remote configuration was
62/// synchronized at least once.
63pub(crate) const SYSTEM_CONFIG_SYNCED_KEY: &str = "system_config_synced";
64
65/// The key used within the "config" collection where we store a mirror of the
66/// `with_0dt_deployment_max_wait` "system var" value. This is mirrored so that
67/// we can toggle the flag with LaunchDarkly, but use it in boot before
68/// LaunchDarkly is available.
69///
70/// NOTE: Weird prefix because we can't start with a `0`.
71pub(crate) const WITH_0DT_DEPLOYMENT_MAX_WAIT: &str = "with_0dt_deployment_max_wait";
72
73/// The key used within the "config" collection where we store a mirror of the
74/// `with_0dt_deployment_ddl_check_interval` "system var" value. This is
75/// mirrored so that we can toggle the flag with LaunchDarkly, but use it in
76/// boot before LaunchDarkly is available.
77///
78/// NOTE: Weird prefix because we can't start with a `0`.
79pub(crate) const WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL: &str =
80    "with_0dt_deployment_ddl_check_interval";
81
82/// The key used within the "config" collection where we store a mirror of the
83/// `enable_0dt_deployment_panic_after_timeout` "system var" value. This is
84/// mirrored so that we can toggle the flag with LaunchDarkly, but use it in
85/// boot before LaunchDarkly is available.
86pub(crate) const ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT: &str =
87    "enable_0dt_deployment_panic_after_timeout";
88
89const USER_ID_ALLOC_KEY: &str = "user";
90const SYSTEM_ID_ALLOC_KEY: &str = "system";
91
92const DEFAULT_USER_CLUSTER_ID: ClusterId = ClusterId::User(1);
93const DEFAULT_USER_CLUSTER_NAME: &str = "quickstart";
94
95const DEFAULT_USER_REPLICA_ID: ReplicaId = ReplicaId::User(1);
96
97const MATERIALIZE_DATABASE_ID_VAL: u64 = 1;
98const MATERIALIZE_DATABASE_ID: DatabaseId = DatabaseId::User(MATERIALIZE_DATABASE_ID_VAL);
99
100const MZ_CATALOG_SCHEMA_ID: u64 = 1;
101const PG_CATALOG_SCHEMA_ID: u64 = 2;
102const PUBLIC_SCHEMA_ID: u64 = 3;
103const MZ_INTERNAL_SCHEMA_ID: u64 = 4;
104const INFORMATION_SCHEMA_ID: u64 = 5;
105pub const MZ_UNSAFE_SCHEMA_ID: u64 = 6;
106pub const MZ_CATALOG_UNSTABLE_SCHEMA_ID: u64 = 7;
107pub const MZ_INTROSPECTION_SCHEMA_ID: u64 = 8;
108
109const DEFAULT_ALLOCATOR_ID: u64 = 1;
110
111pub const DEFAULT_USER_NETWORK_POLICY_ID: NetworkPolicyId = NetworkPolicyId::User(1);
112pub const DEFAULT_USER_NETWORK_POLICY_NAME: &str = "default";
113pub const DEFAULT_USER_NETWORK_POLICY_RULES: &[(
114    &str,
115    mz_sql::plan::NetworkPolicyRuleAction,
116    mz_sql::plan::NetworkPolicyRuleDirection,
117    &str,
118)] = &[(
119    "open_ingress",
120    mz_sql::plan::NetworkPolicyRuleAction::Allow,
121    mz_sql::plan::NetworkPolicyRuleDirection::Ingress,
122    "0.0.0.0/0",
123)];
124
125static DEFAULT_USER_NETWORK_POLICY_PRIVILEGES: LazyLock<Vec<MzAclItem>> = LazyLock::new(|| {
126    vec![rbac::owner_privilege(
127        ObjectType::NetworkPolicy,
128        MZ_SYSTEM_ROLE_ID,
129    )]
130});
131
132static SYSTEM_SCHEMA_PRIVILEGES: LazyLock<Vec<MzAclItem>> = LazyLock::new(|| {
133    vec![
134        rbac::default_builtin_object_privilege(mz_sql::catalog::ObjectType::Schema),
135        MzAclItem {
136            grantee: MZ_SUPPORT_ROLE_ID,
137            grantor: MZ_SYSTEM_ROLE_ID,
138            acl_mode: AclMode::USAGE,
139        },
140        rbac::owner_privilege(mz_sql::catalog::ObjectType::Schema, MZ_SYSTEM_ROLE_ID),
141    ]
142});
143
144static MZ_CATALOG_SCHEMA: LazyLock<Schema> = LazyLock::new(|| Schema {
145    id: SchemaId::System(MZ_CATALOG_SCHEMA_ID),
146    oid: SCHEMA_MZ_CATALOG_OID,
147    database_id: None,
148    name: "mz_catalog".to_string(),
149    owner_id: MZ_SYSTEM_ROLE_ID,
150    privileges: SYSTEM_SCHEMA_PRIVILEGES.clone(),
151});
152static PG_CATALOG_SCHEMA: LazyLock<Schema> = LazyLock::new(|| Schema {
153    id: SchemaId::System(PG_CATALOG_SCHEMA_ID),
154    oid: SCHEMA_PG_CATALOG_OID,
155    database_id: None,
156    name: "pg_catalog".to_string(),
157    owner_id: MZ_SYSTEM_ROLE_ID,
158    privileges: SYSTEM_SCHEMA_PRIVILEGES.clone(),
159});
160static MZ_INTERNAL_SCHEMA: LazyLock<Schema> = LazyLock::new(|| Schema {
161    id: SchemaId::System(MZ_INTERNAL_SCHEMA_ID),
162    oid: SCHEMA_MZ_INTERNAL_OID,
163    database_id: None,
164    name: "mz_internal".to_string(),
165    owner_id: MZ_SYSTEM_ROLE_ID,
166    privileges: SYSTEM_SCHEMA_PRIVILEGES.clone(),
167});
168static INFORMATION_SCHEMA: LazyLock<Schema> = LazyLock::new(|| Schema {
169    id: SchemaId::System(INFORMATION_SCHEMA_ID),
170    oid: SCHEMA_INFORMATION_SCHEMA_OID,
171    database_id: None,
172    name: "information_schema".to_string(),
173    owner_id: MZ_SYSTEM_ROLE_ID,
174    privileges: SYSTEM_SCHEMA_PRIVILEGES.clone(),
175});
176static MZ_UNSAFE_SCHEMA: LazyLock<Schema> = LazyLock::new(|| Schema {
177    id: SchemaId::System(MZ_UNSAFE_SCHEMA_ID),
178    oid: SCHEMA_MZ_UNSAFE_OID,
179    database_id: None,
180    name: "mz_unsafe".to_string(),
181    owner_id: MZ_SYSTEM_ROLE_ID,
182    privileges: SYSTEM_SCHEMA_PRIVILEGES.clone(),
183});
184static MZ_CATALOG_UNSTABLE_SCHEMA: LazyLock<Schema> = LazyLock::new(|| Schema {
185    id: SchemaId::System(MZ_CATALOG_UNSTABLE_SCHEMA_ID),
186    oid: SCHEMA_MZ_CATALOG_UNSTABLE_OID,
187    database_id: None,
188    name: "mz_catalog_unstable".to_string(),
189    owner_id: MZ_SYSTEM_ROLE_ID,
190    privileges: SYSTEM_SCHEMA_PRIVILEGES.clone(),
191});
192static MZ_INTROSPECTION_SCHEMA: LazyLock<Schema> = LazyLock::new(|| Schema {
193    id: SchemaId::System(MZ_INTROSPECTION_SCHEMA_ID),
194    oid: SCHEMA_MZ_INTROSPECTION_OID,
195    database_id: None,
196    name: "mz_introspection".to_string(),
197    owner_id: MZ_SYSTEM_ROLE_ID,
198    privileges: SYSTEM_SCHEMA_PRIVILEGES.clone(),
199});
200static SYSTEM_SCHEMAS: LazyLock<BTreeMap<&str, &Schema>> = LazyLock::new(|| {
201    [
202        &*MZ_CATALOG_SCHEMA,
203        &*PG_CATALOG_SCHEMA,
204        &*MZ_INTERNAL_SCHEMA,
205        &*INFORMATION_SCHEMA,
206        &*MZ_UNSAFE_SCHEMA,
207        &*MZ_CATALOG_UNSTABLE_SCHEMA,
208        &*MZ_INTROSPECTION_SCHEMA,
209    ]
210    .into_iter()
211    .map(|s| (&*s.name, s))
212    .collect()
213});
214
215/// Initializes the Catalog with some default objects.
216#[mz_ore::instrument]
217pub(crate) async fn initialize(
218    tx: &mut Transaction<'_>,
219    options: &BootstrapArgs,
220    initial_ts: EpochMillis,
221    catalog_content_version: String,
222) -> Result<(), CatalogError> {
223    // Collect audit events so we can commit them once at the very end.
224    let mut audit_events = vec![];
225
226    for (name, next_id) in [
227        (USER_ID_ALLOC_KEY.to_string(), DEFAULT_ALLOCATOR_ID),
228        (SYSTEM_ID_ALLOC_KEY.to_string(), DEFAULT_ALLOCATOR_ID),
229        (
230            DATABASE_ID_ALLOC_KEY.to_string(),
231            MATERIALIZE_DATABASE_ID_VAL + 1,
232        ),
233        (
234            SCHEMA_ID_ALLOC_KEY.to_string(),
235            max(&[
236                MZ_CATALOG_SCHEMA_ID,
237                PG_CATALOG_SCHEMA_ID,
238                PUBLIC_SCHEMA_ID,
239                MZ_INTERNAL_SCHEMA_ID,
240                INFORMATION_SCHEMA_ID,
241                MZ_UNSAFE_SCHEMA_ID,
242                MZ_CATALOG_UNSTABLE_SCHEMA_ID,
243                MZ_INTROSPECTION_SCHEMA_ID,
244            ])
245            .expect("known to be non-empty")
246                + 1,
247        ),
248        (USER_ROLE_ID_ALLOC_KEY.to_string(), DEFAULT_ALLOCATOR_ID),
249        (
250            USER_CLUSTER_ID_ALLOC_KEY.to_string(),
251            DEFAULT_USER_CLUSTER_ID.inner_id() + 1,
252        ),
253        (
254            SYSTEM_CLUSTER_ID_ALLOC_KEY.to_string(),
255            DEFAULT_ALLOCATOR_ID,
256        ),
257        (
258            USER_REPLICA_ID_ALLOC_KEY.to_string(),
259            DEFAULT_USER_REPLICA_ID.inner_id()
260                + u64::from(options.default_cluster_replication_factor),
261        ),
262        (
263            SYSTEM_REPLICA_ID_ALLOC_KEY.to_string(),
264            DEFAULT_ALLOCATOR_ID,
265        ),
266        (
267            USER_NETWORK_POLICY_ID_ALLOC_KEY.to_string(),
268            DEFAULT_ALLOCATOR_ID,
269        ),
270        (
271            USER_CLUSTER_REPLICA_SIZE_ID_ALLOC_KEY.to_string(),
272            DEFAULT_ALLOCATOR_ID,
273        ),
274        (
275            SYSTEM_CLUSTER_REPLICA_SIZE_ID_ALLOC_KEY.to_string(),
276            DEFAULT_ALLOCATOR_ID,
277        ),
278        (
279            USER_QUERY_POLICY_ID_ALLOC_KEY.to_string(),
280            DEFAULT_ALLOCATOR_ID,
281        ),
282        (AUDIT_LOG_ID_ALLOC_KEY.to_string(), DEFAULT_ALLOCATOR_ID),
283        (STORAGE_USAGE_ID_ALLOC_KEY.to_string(), DEFAULT_ALLOCATOR_ID),
284        (OID_ALLOC_KEY.to_string(), FIRST_USER_OID.into()),
285    ] {
286        tx.insert_id_allocator(name, next_id)?;
287    }
288
289    for role in BUILTIN_ROLES {
290        tx.insert_builtin_role(
291            role.id,
292            role.name.to_string(),
293            role.attributes.clone(),
294            RoleMembership::new(),
295            RoleVars::default(),
296            role.oid,
297        )?;
298    }
299    tx.insert_builtin_role(
300        RoleId::Public,
301        PUBLIC_ROLE_NAME.as_str().to_lowercase(),
302        RoleAttributesRaw::new(),
303        RoleMembership::new(),
304        RoleVars::default(),
305        ROLE_PUBLIC_OID,
306    )?;
307
308    // If provided, generate a new Id for the bootstrap role.
309    let bootstrap_role = if let Some(role) = &options.bootstrap_role {
310        let attributes = RoleAttributesRaw::new();
311        let membership = RoleMembership::new();
312        let vars = RoleVars::default();
313
314        let (id, oid) = tx.insert_user_role(
315            role.to_string(),
316            attributes.clone(),
317            membership.clone(),
318            vars.clone(),
319            &HashSet::new(),
320        )?;
321
322        audit_events.push((
323            mz_audit_log::EventType::Create,
324            mz_audit_log::ObjectType::Role,
325            mz_audit_log::EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
326                id: id.to_string(),
327                name: role.to_string(),
328            }),
329        ));
330
331        Some(Role {
332            id,
333            name: role.to_string(),
334            attributes: attributes.into(),
335            membership,
336            vars,
337            oid,
338        })
339    } else {
340        None
341    };
342
343    let default_privileges = [
344        // mz_support needs USAGE privileges on all clusters, databases, and schemas for
345        // debugging.
346        DefaultPrivilege {
347            object: DefaultPrivilegeObject {
348                role_id: RoleId::Public,
349                database_id: None,
350                schema_id: None,
351                object_type: mz_sql::catalog::ObjectType::Cluster,
352            },
353            acl_item: DefaultPrivilegeAclItem {
354                grantee: MZ_SUPPORT_ROLE_ID,
355                acl_mode: AclMode::USAGE,
356            },
357        },
358        DefaultPrivilege {
359            object: DefaultPrivilegeObject {
360                role_id: RoleId::Public,
361                database_id: None,
362                schema_id: None,
363                object_type: mz_sql::catalog::ObjectType::Database,
364            },
365            acl_item: DefaultPrivilegeAclItem {
366                grantee: MZ_SUPPORT_ROLE_ID,
367                acl_mode: AclMode::USAGE,
368            },
369        },
370        DefaultPrivilege {
371            object: DefaultPrivilegeObject {
372                role_id: RoleId::Public,
373                database_id: None,
374                schema_id: None,
375                object_type: mz_sql::catalog::ObjectType::Schema,
376            },
377            acl_item: DefaultPrivilegeAclItem {
378                grantee: MZ_SUPPORT_ROLE_ID,
379                acl_mode: AclMode::USAGE,
380            },
381        },
382        DefaultPrivilege {
383            object: DefaultPrivilegeObject {
384                role_id: RoleId::Public,
385                database_id: None,
386                schema_id: None,
387                object_type: mz_sql::catalog::ObjectType::Type,
388            },
389            acl_item: DefaultPrivilegeAclItem {
390                grantee: RoleId::Public,
391                acl_mode: AclMode::USAGE,
392            },
393        },
394    ];
395    tx.set_default_privileges(default_privileges.to_vec())?;
396    for DefaultPrivilege { object, acl_item } in default_privileges {
397        let object_type = match object.object_type {
398            ObjectType::Table => mz_audit_log::ObjectType::Table,
399            ObjectType::View => mz_audit_log::ObjectType::View,
400            ObjectType::MaterializedView => mz_audit_log::ObjectType::MaterializedView,
401            ObjectType::Source => mz_audit_log::ObjectType::Source,
402            ObjectType::Sink => mz_audit_log::ObjectType::Sink,
403            ObjectType::MetricSink => mz_audit_log::ObjectType::MetricSink,
404            ObjectType::Index => mz_audit_log::ObjectType::Index,
405            ObjectType::Type => mz_audit_log::ObjectType::Type,
406            ObjectType::Role => mz_audit_log::ObjectType::Role,
407            ObjectType::Cluster => mz_audit_log::ObjectType::Cluster,
408            ObjectType::ClusterReplica => mz_audit_log::ObjectType::ClusterReplica,
409            ObjectType::Secret => mz_audit_log::ObjectType::Secret,
410            ObjectType::Connection => mz_audit_log::ObjectType::Connection,
411            ObjectType::Database => mz_audit_log::ObjectType::Database,
412            ObjectType::Schema => mz_audit_log::ObjectType::Schema,
413            ObjectType::Func => mz_audit_log::ObjectType::Func,
414            ObjectType::NetworkPolicy => mz_audit_log::ObjectType::NetworkPolicy,
415            ObjectType::QueryPolicy => mz_audit_log::ObjectType::QueryPolicy,
416        };
417        audit_events.push((
418            mz_audit_log::EventType::Grant,
419            object_type,
420            mz_audit_log::EventDetails::AlterDefaultPrivilegeV1(
421                mz_audit_log::AlterDefaultPrivilegeV1 {
422                    role_id: object.role_id.to_string(),
423                    database_id: object.database_id.map(|id| id.to_string()),
424                    schema_id: object.schema_id.map(|id| id.to_string()),
425                    grantee_id: acl_item.grantee.to_string(),
426                    privileges: acl_item.acl_mode.to_string(),
427                },
428            ),
429        ));
430    }
431
432    let mut db_privileges = vec![
433        MzAclItem {
434            grantee: RoleId::Public,
435            grantor: MZ_SYSTEM_ROLE_ID,
436            acl_mode: AclMode::USAGE,
437        },
438        MzAclItem {
439            grantee: MZ_SUPPORT_ROLE_ID,
440            grantor: MZ_SYSTEM_ROLE_ID,
441            acl_mode: AclMode::USAGE,
442        },
443        rbac::owner_privilege(mz_sql::catalog::ObjectType::Database, MZ_SYSTEM_ROLE_ID),
444    ];
445    // Optionally add a privilege for the bootstrap role.
446    if let Some(role) = &bootstrap_role {
447        db_privileges.push(MzAclItem {
448            grantee: role.id.clone(),
449            grantor: MZ_SYSTEM_ROLE_ID,
450            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(
451                mz_sql::catalog::ObjectType::Database,
452            )),
453        })
454    };
455
456    let materialize_db_oid = tx.allocate_oid(&HashSet::new())?;
457    tx.insert_database(
458        MATERIALIZE_DATABASE_ID,
459        "materialize",
460        MZ_SYSTEM_ROLE_ID,
461        db_privileges,
462        materialize_db_oid,
463    )?;
464    audit_events.extend([
465        (
466            mz_audit_log::EventType::Create,
467            mz_audit_log::ObjectType::Database,
468            mz_audit_log::EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
469                id: MATERIALIZE_DATABASE_ID.to_string(),
470                name: "materialize".to_string(),
471            }),
472        ),
473        (
474            mz_audit_log::EventType::Grant,
475            mz_audit_log::ObjectType::Database,
476            mz_audit_log::EventDetails::UpdatePrivilegeV1(mz_audit_log::UpdatePrivilegeV1 {
477                object_id: ObjectId::Database(MATERIALIZE_DATABASE_ID).to_string(),
478                grantee_id: RoleId::Public.to_string(),
479                grantor_id: MZ_SYSTEM_ROLE_ID.to_string(),
480                privileges: AclMode::USAGE.to_string(),
481            }),
482        ),
483    ]);
484    // Optionally add a privilege for the bootstrap role.
485    if let Some(role) = &bootstrap_role {
486        let role_id: RoleId = role.id.clone();
487        audit_events.push((
488            mz_audit_log::EventType::Grant,
489            mz_audit_log::ObjectType::Database,
490            mz_audit_log::EventDetails::UpdatePrivilegeV1(mz_audit_log::UpdatePrivilegeV1 {
491                object_id: ObjectId::Database(MATERIALIZE_DATABASE_ID).to_string(),
492                grantee_id: role_id.to_string(),
493                grantor_id: MZ_SYSTEM_ROLE_ID.to_string(),
494                privileges: rbac::all_object_privileges(SystemObjectType::Object(
495                    mz_sql::catalog::ObjectType::Database,
496                ))
497                .to_string(),
498            }),
499        ));
500    }
501
502    let public_schema_oid = tx.allocate_oid(&HashSet::new())?;
503    let public_schema = Schema {
504        id: SchemaId::User(PUBLIC_SCHEMA_ID),
505        oid: public_schema_oid,
506        database_id: Some(MATERIALIZE_DATABASE_ID),
507        name: "public".to_string(),
508        owner_id: MZ_SYSTEM_ROLE_ID,
509        privileges: vec![
510            MzAclItem {
511                grantee: RoleId::Public,
512                grantor: MZ_SYSTEM_ROLE_ID,
513                acl_mode: AclMode::USAGE,
514            },
515            MzAclItem {
516                grantee: MZ_SUPPORT_ROLE_ID,
517                grantor: MZ_SYSTEM_ROLE_ID,
518                acl_mode: AclMode::USAGE,
519            },
520            rbac::owner_privilege(mz_sql::catalog::ObjectType::Schema, MZ_SYSTEM_ROLE_ID),
521        ]
522        .into_iter()
523        // Optionally add the bootstrap role to the public schema.
524        .chain(bootstrap_role.as_ref().map(|role| MzAclItem {
525            grantee: role.id.clone(),
526            grantor: MZ_SYSTEM_ROLE_ID,
527            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(
528                mz_sql::catalog::ObjectType::Schema,
529            )),
530        }))
531        .collect(),
532    };
533
534    for schema in SYSTEM_SCHEMAS.values().chain(iter::once(&&public_schema)) {
535        tx.insert_schema(
536            schema.id,
537            schema.database_id,
538            schema.name.clone(),
539            schema.owner_id,
540            schema.privileges.clone(),
541            schema.oid,
542        )?;
543    }
544    audit_events.push((
545        mz_audit_log::EventType::Create,
546        mz_audit_log::ObjectType::Schema,
547        mz_audit_log::EventDetails::SchemaV2(mz_audit_log::SchemaV2 {
548            id: PUBLIC_SCHEMA_ID.to_string(),
549            name: "public".to_string(),
550            database_name: Some("materialize".to_string()),
551        }),
552    ));
553    if let Some(role) = &bootstrap_role {
554        let role_id: RoleId = role.id.clone();
555        audit_events.push((
556            mz_audit_log::EventType::Grant,
557            mz_audit_log::ObjectType::Schema,
558            mz_audit_log::EventDetails::UpdatePrivilegeV1(mz_audit_log::UpdatePrivilegeV1 {
559                object_id: ObjectId::Schema((
560                    ResolvedDatabaseSpecifier::Id(MATERIALIZE_DATABASE_ID),
561                    SchemaSpecifier::Id(SchemaId::User(PUBLIC_SCHEMA_ID)),
562                ))
563                .to_string(),
564                grantee_id: role_id.to_string(),
565                grantor_id: MZ_SYSTEM_ROLE_ID.to_string(),
566                privileges: rbac::all_object_privileges(SystemObjectType::Object(
567                    mz_sql::catalog::ObjectType::Schema,
568                ))
569                .to_string(),
570            }),
571        ));
572    }
573
574    let mut cluster_privileges = vec![
575        MzAclItem {
576            grantee: RoleId::Public,
577            grantor: MZ_SYSTEM_ROLE_ID,
578            acl_mode: AclMode::USAGE,
579        },
580        MzAclItem {
581            grantee: MZ_SUPPORT_ROLE_ID,
582            grantor: MZ_SYSTEM_ROLE_ID,
583            acl_mode: AclMode::USAGE,
584        },
585        rbac::owner_privilege(mz_sql::catalog::ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
586    ];
587
588    // Optionally add a privilege for the bootstrap role.
589    if let Some(role) = &bootstrap_role {
590        cluster_privileges.push(MzAclItem {
591            grantee: role.id.clone(),
592            grantor: MZ_SYSTEM_ROLE_ID,
593            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(
594                mz_sql::catalog::ObjectType::Cluster,
595            )),
596        });
597    };
598
599    tx.insert_network_policy(
600        DEFAULT_USER_NETWORK_POLICY_ID,
601        DEFAULT_USER_NETWORK_POLICY_NAME.to_string(),
602        DEFAULT_USER_NETWORK_POLICY_RULES
603            .into_iter()
604            .map(|(name, action, direction, ip_str)| NetworkPolicyRule {
605                name: name.to_string(),
606                action: action.clone(),
607                direction: direction.clone(),
608                address: PolicyAddress(
609                    IpNet::from_str(ip_str).expect("default policy must provide valid ip"),
610                ),
611            })
612            .collect::<Vec<NetworkPolicyRule>>(),
613        DEFAULT_USER_NETWORK_POLICY_PRIVILEGES.clone(),
614        MZ_SYSTEM_ROLE_ID,
615        NETWORK_POLICIES_DEFAULT_POLICY_OID,
616    )?;
617    // We created a network policy with a prefined ID user(1) and OID. We need
618    // to increment the id alloc key. It should be safe to assume that there's
619    // no user(1), as a sanity check, we'll assert this is the case.
620    let id = tx.get_and_increment_id(USER_NETWORK_POLICY_ID_ALLOC_KEY.to_string())?;
621    assert!(DEFAULT_USER_NETWORK_POLICY_ID == NetworkPolicyId::User(id));
622
623    audit_events.extend([(
624        mz_audit_log::EventType::Create,
625        mz_audit_log::ObjectType::NetworkPolicy,
626        mz_audit_log::EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
627            id: DEFAULT_USER_NETWORK_POLICY_ID.to_string(),
628            name: DEFAULT_USER_NETWORK_POLICY_NAME.to_string(),
629        }),
630    )]);
631
632    tx.insert_user_cluster(
633        DEFAULT_USER_CLUSTER_ID,
634        DEFAULT_USER_CLUSTER_NAME,
635        Vec::new(),
636        MZ_SYSTEM_ROLE_ID,
637        cluster_privileges,
638        default_cluster_config(options)?,
639        &HashSet::new(),
640    )?;
641    audit_events.extend([
642        (
643            mz_audit_log::EventType::Create,
644            mz_audit_log::ObjectType::Cluster,
645            mz_audit_log::EventDetails::IdNameV1(mz_audit_log::IdNameV1 {
646                id: DEFAULT_USER_CLUSTER_ID.to_string(),
647                name: DEFAULT_USER_CLUSTER_NAME.to_string(),
648            }),
649        ),
650        (
651            mz_audit_log::EventType::Grant,
652            mz_audit_log::ObjectType::Cluster,
653            mz_audit_log::EventDetails::UpdatePrivilegeV1(mz_audit_log::UpdatePrivilegeV1 {
654                object_id: ObjectId::Cluster(DEFAULT_USER_CLUSTER_ID).to_string(),
655                grantee_id: RoleId::Public.to_string(),
656                grantor_id: MZ_SYSTEM_ROLE_ID.to_string(),
657                privileges: AclMode::USAGE.to_string(),
658            }),
659        ),
660    ]);
661
662    // Optionally add a privilege for the bootstrap role.
663    if let Some(role) = &bootstrap_role {
664        let role_id: RoleId = role.id.clone();
665        audit_events.push((
666            mz_audit_log::EventType::Grant,
667            mz_audit_log::ObjectType::Cluster,
668            mz_audit_log::EventDetails::UpdatePrivilegeV1(mz_audit_log::UpdatePrivilegeV1 {
669                object_id: ObjectId::Cluster(DEFAULT_USER_CLUSTER_ID).to_string(),
670                grantee_id: role_id.to_string(),
671                grantor_id: MZ_SYSTEM_ROLE_ID.to_string(),
672                privileges: rbac::all_object_privileges(SystemObjectType::Object(
673                    mz_sql::catalog::ObjectType::Cluster,
674                ))
675                .to_string(),
676            }),
677        ));
678    }
679
680    for i in 0..options.default_cluster_replication_factor {
681        let replica_id = ReplicaId::User(DEFAULT_USER_REPLICA_ID.inner_id() + u64::from(i));
682        let replica_name = format!("r{}", i + 1);
683        tx.insert_cluster_replica_with_id(
684            DEFAULT_USER_CLUSTER_ID,
685            replica_id,
686            &replica_name,
687            default_replica_config(options)?,
688            MZ_SYSTEM_ROLE_ID,
689        )?;
690        audit_events.push((
691            mz_audit_log::EventType::Create,
692            mz_audit_log::ObjectType::ClusterReplica,
693            mz_audit_log::EventDetails::CreateClusterReplicaV4(
694                mz_audit_log::CreateClusterReplicaV4 {
695                    cluster_id: DEFAULT_USER_CLUSTER_ID.to_string(),
696                    cluster_name: DEFAULT_USER_CLUSTER_NAME.to_string(),
697                    replica_name,
698                    replica_id: Some(replica_id.to_string()),
699                    logical_size: options.default_cluster_replica_size.to_string(),
700                    billed_as: None,
701                    internal: false,
702                    reason: CreateOrDropClusterReplicaReasonV1::System,
703                    scheduling_policies: None,
704                },
705            ),
706        ));
707    }
708
709    let system_privileges = [MzAclItem {
710        grantee: MZ_SYSTEM_ROLE_ID,
711        grantor: MZ_SYSTEM_ROLE_ID,
712        acl_mode: rbac::all_object_privileges(SystemObjectType::System),
713    }]
714    .into_iter()
715    // Optionally add system privileges for the bootstrap role.
716    .chain(bootstrap_role.as_ref().map(|role| MzAclItem {
717        grantee: role.id.clone(),
718        grantor: MZ_SYSTEM_ROLE_ID,
719        acl_mode: rbac::all_object_privileges(SystemObjectType::System),
720    }));
721    tx.set_system_privileges(system_privileges.clone().collect())?;
722    for system_privilege in system_privileges {
723        audit_events.push((
724            mz_audit_log::EventType::Grant,
725            mz_audit_log::ObjectType::System,
726            mz_audit_log::EventDetails::UpdatePrivilegeV1(mz_audit_log::UpdatePrivilegeV1 {
727                object_id: "SYSTEM".to_string(),
728                grantee_id: system_privilege.grantee.to_string(),
729                grantor_id: system_privilege.grantor.to_string(),
730                privileges: system_privilege.acl_mode.to_string(),
731            }),
732        ));
733    }
734
735    // Allocate an ID for each audit log event.
736    let mut audit_events_with_id = Vec::with_capacity(audit_events.len());
737    for (ty, obj, details) in audit_events {
738        let id = tx.get_and_increment_id(AUDIT_LOG_ID_ALLOC_KEY.to_string())?;
739        audit_events_with_id.push((id, ty, obj, details));
740    }
741
742    for (id, event_type, object_type, details) in audit_events_with_id {
743        tx.insert_audit_log_event(VersionedEvent::V1(EventV1 {
744            id,
745            event_type,
746            object_type,
747            details,
748            user: None,
749            occurred_at: initial_ts,
750        }));
751    }
752
753    for (key, value) in [
754        (USER_VERSION_KEY.to_string(), CATALOG_VERSION),
755        (SYSTEM_CONFIG_SYNCED_KEY.to_string(), 0),
756    ] {
757        tx.insert_config(key, value)?;
758    }
759
760    for (name, value) in [
761        (
762            CATALOG_CONTENT_VERSION_KEY.to_string(),
763            catalog_content_version,
764        ),
765        (
766            BUILTIN_MIGRATION_SHARD_KEY.to_string(),
767            ShardId::new().to_string(),
768        ),
769        (
770            EXPRESSION_CACHE_SHARD_KEY.to_string(),
771            ShardId::new().to_string(),
772        ),
773    ] {
774        tx.set_setting(name, Some(value))?;
775    }
776
777    if tx
778        .get_setting(MOCK_AUTHENTICATION_NONCE_KEY.to_string())
779        .is_none()
780    {
781        let nonce: [u8; 24] = rand::random();
782        tx.set_setting(
783            MOCK_AUTHENTICATION_NONCE_KEY.to_string(),
784            Some(BASE64_STANDARD.encode(nonce)),
785        )?;
786    }
787
788    Ok(())
789}
790
791pub fn resolve_system_schema(name: &str) -> &Schema {
792    SYSTEM_SCHEMAS
793        .get(name)
794        .unwrap_or_else(|| panic!("unable to resolve system schema: {name}"))
795}
796
797/// Defines the default config for a Cluster.
798fn default_cluster_config(args: &BootstrapArgs) -> Result<ClusterConfig, CatalogError> {
799    Ok(ClusterConfig {
800        variant: ClusterVariant::Managed(ClusterVariantManaged {
801            size: args.default_cluster_replica_size.to_string(),
802            replication_factor: args.default_cluster_replication_factor,
803            availability_zones: vec![],
804            logging: ReplicaLogging {
805                log_logging: false,
806                interval: Some(Duration::from_secs(1)),
807            },
808            arrangement_compression: false,
809            optimizer_feature_overrides: Default::default(),
810            schedule: Default::default(),
811            auto_scaling_strategy: None,
812            reconfiguration: None,
813            burst: None,
814        }),
815        workload_class: None,
816        query_policy: None,
817    })
818}
819
820/// Defines the default config for a Cluster Replica.
821fn default_replica_config(args: &BootstrapArgs) -> Result<ReplicaConfig, CatalogError> {
822    Ok(ReplicaConfig {
823        location: ReplicaLocation::Managed {
824            size: args.default_cluster_replica_size.to_string(),
825            availability_zones: Vec::new(),
826            internal: false,
827            billed_as: None,
828            pending: false,
829        },
830        logging: ReplicaLogging {
831            log_logging: false,
832            interval: Some(Duration::from_secs(1)),
833        },
834        arrangement_compression: false,
835    })
836}