blob: dec78154a327d2c556e95e4ac5e7b89489e9aa06 [file]
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
use super::status;
use crate::{Result, catalog};
use maka_agent_facts::configuration::CredentialLocator;
use maka_agent_facts::configuration::CredentialState;
use sqlx::SqliteConnection;
use uuid::Uuid;
/// New enrollment is a new authority even when the token bytes are identical.
/// The caller's transaction rolls back both deletion and insertion on failure.
pub(crate) async fn replace_secret(
tx: &mut SqliteConnection,
locator: &CredentialLocator,
secret: &str,
now: u64,
) -> Result<()> {
sqlx::query("DELETE FROM credentials WHERE locator = ?")
.bind(serde_json::to_string(locator)?)
.execute(&mut *tx)
.await?;
write_secret(tx, locator, secret, now).await
}
pub(crate) async fn write_secret(
tx: &mut SqliteConnection,
locator: &CredentialLocator,
secret: &str,
now: u64,
) -> Result<()> {
let previous = status(tx, locator).await?;
let (credential_id, previous_revision) = match previous.state {
CredentialState::Absent => (Uuid::new_v4().to_string(), 0),
CredentialState::Configured {
credential_id,
revision,
..
} => (credential_id, revision),
};
let revision = catalog::next_revision(previous_revision)?;
let locator = serde_json::to_string(locator)?;
sqlx::query("INSERT INTO credentials VALUES(?, ?, ?, ?, ?)
ON CONFLICT(locator) DO UPDATE SET revision = excluded.revision, secret = excluded.secret, updated_at = excluded.updated_at")
.bind(locator).bind(credential_id).bind(revision as i64).bind(secret).bind(now as i64)
.execute(&mut *tx).await?;
Ok(())
}