Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions crates/forgust-db/migrations/20261113000000_ssh_key_usage.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
-- What an SSH key is for, as in GitLab's `usage_type`: signing in over SSH
-- (`auth`), verifying signed commits (`signing`), or both. Existing personal
-- keys did both; deploy keys only sign in (the CHECK holds them to it).
ALTER TABLE ssh_keys ADD COLUMN usage_type text NOT NULL DEFAULT 'auth_and_signing'
CHECK (usage_type IN ('auth', 'signing', 'auth_and_signing'));
UPDATE ssh_keys SET usage_type = 'auth' WHERE kind = 'deploy';
ALTER TABLE ssh_keys ADD CONSTRAINT ssh_keys_deploy_keys_only_sign_in
CHECK (kind <> 'deploy' OR usage_type = 'auth');
88 changes: 81 additions & 7 deletions crates/forgust-db/src/ssh_keys.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,53 @@
use chrono::{DateTime, Utc};
use serde::Serialize;
use serde::{Deserialize, Serialize};
use sqlx::PgExecutor;
use sqlx::postgres::{PgTypeInfo, PgValueRef, Postgres};

use crate::Result;

/// What an SSH key is for, as GitLab's `usage_type`: signing in over SSH,
/// verifying the commits its owner signs, or both. Deploy keys only sign in
/// (the table's CHECK holds them to it).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum KeyUsage {
Auth,
Signing,
AuthAndSigning,
}

impl KeyUsage {
pub fn as_str(self) -> &'static str {
match self {
KeyUsage::Auth => "auth",
KeyUsage::Signing => "signing",
KeyUsage::AuthAndSigning => "auth_and_signing",
}
}
}

// stored as text: the column's CHECK lists the same values
impl sqlx::Type<Postgres> for KeyUsage {
fn type_info() -> PgTypeInfo {
<&str as sqlx::Type<Postgres>>::type_info()
}

fn compatible(ty: &PgTypeInfo) -> bool {
<&str as sqlx::Type<Postgres>>::compatible(ty)
}
}

impl<'r> sqlx::Decode<'r, Postgres> for KeyUsage {
fn decode(value: PgValueRef<'r>) -> std::result::Result<Self, sqlx::error::BoxDynError> {
match <&str as sqlx::Decode<Postgres>>::decode(value)? {
"auth" => Ok(KeyUsage::Auth),
"signing" => Ok(KeyUsage::Signing),
"auth_and_signing" => Ok(KeyUsage::AuthAndSigning),
other => Err(format!("unknown SSH key usage {other:?}").into()),
}
}
}

#[derive(Debug, Clone, Serialize, utoipa::ToSchema)]
pub struct SshKey {
pub id: i64,
Expand All @@ -15,8 +59,22 @@ pub struct SshKey {
pub expires_at: Option<DateTime<Utc>>,
pub last_used_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
pub usage_type: KeyUsage,
}

impl SshKey {
/// The key may sign in over SSH.
pub fn for_auth(&self) -> bool {
self.usage_type != KeyUsage::Signing
}

/// The key verifies the commits its owner signs.
pub fn for_signing(&self) -> bool {
self.usage_type != KeyUsage::Auth
}
}

#[allow(clippy::too_many_arguments)]
pub async fn insert(
e: impl PgExecutor<'_>,
kind: &str,
Expand All @@ -25,25 +83,41 @@ pub async fn insert(
public_key: &str,
fingerprint: &str,
expires_at: Option<DateTime<Utc>>,
usage_type: KeyUsage,
) -> Result<i64> {
sqlx::query_scalar!(
"INSERT INTO ssh_keys (kind, user_id, title, public_key, fingerprint, expires_at) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id",
"INSERT INTO ssh_keys (kind, user_id, title, public_key, fingerprint, expires_at, usage_type) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id",
kind,
user_id,
title,
public_key,
fingerprint,
expires_at
expires_at,
usage_type.as_str()
)
.fetch_one(e)
.await
}

/// A key that has not expired (for signing in, and for adding keys).
pub async fn find_by_fingerprint(e: impl PgExecutor<'_>, fingerprint: &str) -> Result<Option<SshKey>> {
sqlx::query_as!(
SshKey,
"SELECT id, kind, user_id, title, public_key, fingerprint, expires_at, last_used_at, created_at FROM ssh_keys
WHERE fingerprint = $1 AND (expires_at IS NULL OR expires_at > now())",
r#"SELECT id, kind, user_id, title, public_key, fingerprint, expires_at, last_used_at, created_at, usage_type AS "usage_type: KeyUsage" FROM ssh_keys
WHERE fingerprint = $1 AND (expires_at IS NULL OR expires_at > now())"#,
fingerprint
)
.fetch_optional(e)
.await
}

/// A key, expired or not: the commits it signed stay verified once it expires
/// (deleting it is what takes that back).
pub async fn find_signing_key(e: impl PgExecutor<'_>, fingerprint: &str) -> Result<Option<SshKey>> {
sqlx::query_as!(
SshKey,
r#"SELECT id, kind, user_id, title, public_key, fingerprint, expires_at, last_used_at, created_at, usage_type AS "usage_type: KeyUsage" FROM ssh_keys
WHERE fingerprint = $1"#,
fingerprint
)
.fetch_optional(e)
Expand All @@ -63,8 +137,8 @@ pub async fn touch(e: impl PgExecutor<'_>, id: i64) -> Result<()> {
pub async fn list_for_user(e: impl PgExecutor<'_>, user_id: i64) -> Result<Vec<SshKey>> {
sqlx::query_as!(
SshKey,
"SELECT id, kind, user_id, title, public_key, fingerprint, expires_at, last_used_at, created_at FROM ssh_keys
WHERE user_id = $1 ORDER BY created_at DESC",
r#"SELECT id, kind, user_id, title, public_key, fingerprint, expires_at, last_used_at, created_at, usage_type AS "usage_type: KeyUsage" FROM ssh_keys
WHERE user_id = $1 ORDER BY created_at DESC"#,
user_id
)
.fetch_all(e)
Expand Down
2 changes: 1 addition & 1 deletion crates/forgust-server/src/api/openapi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ use super::{
forgust_db::admin::BlobScan, forgust_db::admin::PrefixUsage, forgust_db::admin::TaskQueue, forgust_db::admin::FailedJob,
dto::Resolved, dto::UserDto, dto::GroupDto, dto::GroupDetail, dto::OrgPolicyDto, dto::Breadcrumb, dto::ProjectDto, dto::ProjectDetail,
dto::MemberDto, dto::ShareDto, dto::ProtectedBranchDto, dto::NewToken, dto::AccessTokenDto,
forgust_db::ssh_keys::SshKey, forgust_db::ssh_keys::DeployKey, forgust_db::tokens::AccessToken, forgust_db::tokens::DeployToken,
forgust_db::ssh_keys::SshKey, forgust_db::ssh_keys::KeyUsage, forgust_db::ssh_keys::DeployKey, forgust_db::tokens::AccessToken, forgust_db::tokens::DeployToken,
forgust_db::audit::AuditEvent, forgust_db::settings::InstanceSettings,
forgust_storage::TreeEntry, forgust_storage::EntryKind, forgust_storage::CommitInfo, forgust_storage::CommitSummary, forgust_storage::Person,
forgust_storage::BlameHunk, forgust_storage::Diff, forgust_storage::DiffFile, forgust_storage::DiffHunk, forgust_storage::DiffLine,
Expand Down
5 changes: 4 additions & 1 deletion crates/forgust-server/src/api/projects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,10 @@ pub async fn add_deploy_key(
// an existing deploy key can be attached to more projects; a user key cannot
Some(k) if k.kind == "deploy" => k.id,
Some(_) => return Err(ApiError::conflict("this key is already used as a personal key")),
None => forgust_db::ssh_keys::insert(&state.db, "deploy", None, &req.title, &key, &fp, None).await?,
None => {
forgust_db::ssh_keys::insert(&state.db, "deploy", None, &req.title, &key, &fp, None, forgust_db::ssh_keys::KeyUsage::Auth)
.await?
}
};
forgust_db::ssh_keys::link_deploy_key(&state.db, key_id, proj.id, req.can_push).await?;
services::audit(
Expand Down
Loading
Loading