enrollment codes
This commit is contained in:
parent
6d01d8703b
commit
7e1627e165
|
@ -81,6 +81,8 @@ pub struct TrifidConfigTokens {
|
||||||
pub totp_setup_timeout_time_seconds: u64,
|
pub totp_setup_timeout_time_seconds: u64,
|
||||||
#[serde(default = "mfa_tokens_expiry_time")]
|
#[serde(default = "mfa_tokens_expiry_time")]
|
||||||
pub mfa_tokens_expiry_time_seconds: u64,
|
pub mfa_tokens_expiry_time_seconds: u64,
|
||||||
|
#[serde(default = "enrollment_tokens_expiry_time")]
|
||||||
|
pub enrollment_tokens_expiry_time: u64
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
|
@ -115,3 +117,6 @@ fn totp_setup_timeout_time() -> u64 {
|
||||||
fn mfa_tokens_expiry_time() -> u64 {
|
fn mfa_tokens_expiry_time() -> u64 {
|
||||||
600
|
600
|
||||||
} // 10 minutes
|
} // 10 minutes
|
||||||
|
fn enrollment_tokens_expiry_time() -> u64 {
|
||||||
|
600
|
||||||
|
} // 10 minutes
|
|
@ -101,6 +101,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||||
.service(routes::v1::hosts::delete_host)
|
.service(routes::v1::hosts::delete_host)
|
||||||
.service(routes::v1::hosts::edit_host)
|
.service(routes::v1::hosts::edit_host)
|
||||||
.service(routes::v1::hosts::block_host)
|
.service(routes::v1::hosts::block_host)
|
||||||
|
.service(routes::v1::hosts::enroll_host)
|
||||||
})
|
})
|
||||||
.bind(CONFIG.server.bind)?
|
.bind(CONFIG.server.bind)?
|
||||||
.run()
|
.run()
|
||||||
|
|
|
@ -39,13 +39,23 @@
|
||||||
// This endpoint is considered done. No major features should be added or removed, unless it fixes bugs.
|
// This endpoint is considered done. No major features should be added or removed, unless it fixes bugs.
|
||||||
// This endpoint requires the `definednetworking` extension to be enabled to be used.
|
// This endpoint requires the `definednetworking` extension to be enabled to be used.
|
||||||
// This endpoint has additional functionality enabled by the extended_hosts feature flag.
|
// This endpoint has additional functionality enabled by the extended_hosts feature flag.
|
||||||
|
//
|
||||||
|
//#POST /v1/hosts/{host_id}/block t+parity:full t+type:documented t+status:done t+feature:definednetworking
|
||||||
|
// This endpoint has full parity with the original API. It has been recreated from the original API documentation.
|
||||||
|
// This endpoint is considered done. No major features should be added or removed, unless it fixes bugs.
|
||||||
|
// This endpoint requires the `definednetworking` extension to be enabled to be used.
|
||||||
|
//
|
||||||
|
//#POST /v1/hosts/{host_id}/enrollment-code t+parity:full t+type:documented t+status:done t+feature:definednetworking
|
||||||
|
// This endpoint has full parity with the original API. It has been recreated from the original API documentation.
|
||||||
|
// This endpoint is considered done. No major features should be added or removed, unless it fixes bugs.
|
||||||
|
// This endpoint requires the `definednetworking` extension to be enabled to be used.
|
||||||
|
|
||||||
use crate::auth_tokens::{enforce_2fa, enforce_api_token, TokenInfo};
|
use crate::auth_tokens::{enforce_2fa, enforce_api_token, TokenInfo};
|
||||||
use crate::cursor::Cursor;
|
use crate::cursor::Cursor;
|
||||||
use crate::error::{APIError, APIErrorsResponse};
|
use crate::error::{APIError, APIErrorsResponse};
|
||||||
use crate::routes::v1::trifid::SUPPORTED_EXTENSIONS;
|
use crate::routes::v1::trifid::SUPPORTED_EXTENSIONS;
|
||||||
use crate::timers::TIME_FORMAT;
|
use crate::timers::{expires_in_seconds, TIME_FORMAT};
|
||||||
use crate::tokens::random_id;
|
use crate::tokens::{random_id, random_token};
|
||||||
use crate::AppState;
|
use crate::AppState;
|
||||||
use actix_web::web::{Data, Json, Path, Query};
|
use actix_web::web::{Data, Json, Path, Query};
|
||||||
use actix_web::{delete, get, post, put, HttpRequest, HttpResponse};
|
use actix_web::{delete, get, post, put, HttpRequest, HttpResponse};
|
||||||
|
@ -61,6 +71,7 @@ use std::net::{Ipv4Addr, SocketAddrV4};
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
use trifid_api_entities::entity::{host, host_static_address, network, organization};
|
use trifid_api_entities::entity::{host, host_static_address, network, organization};
|
||||||
|
use crate::config::CONFIG;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct ListHostsRequestOpts {
|
pub struct ListHostsRequestOpts {
|
||||||
|
@ -1780,3 +1791,217 @@ pub async fn block_host(
|
||||||
metadata: BlockHostResponseMetadata {},
|
metadata: BlockHostResponseMetadata {},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub struct CodeResponse {
|
||||||
|
pub code: String,
|
||||||
|
#[serde(rename = "lifetimeSeconds")]
|
||||||
|
pub lifetime_seconds: u64
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub struct EnrollmentCodeResponse {
|
||||||
|
pub data: EnrollmentCodeResponseData,
|
||||||
|
pub metadata: EnrollmentCodeResponseMetadata
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub struct EnrollmentCodeResponseData {
|
||||||
|
#[serde(rename = "enrollmentCode")]
|
||||||
|
pub enrollment_code: CodeResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub struct EnrollmentCodeResponseMetadata {}
|
||||||
|
|
||||||
|
#[post("/v1/hosts/{host_id}/enrollment-code")]
|
||||||
|
pub async fn enroll_host(id: Path<String>, req_info: HttpRequest, db: Data<AppState>) -> HttpResponse {
|
||||||
|
let session_info = enforce_2fa(&req_info, &db.conn)
|
||||||
|
.await
|
||||||
|
.unwrap_or(TokenInfo::NotPresent);
|
||||||
|
let api_token_info = enforce_api_token(&req_info, &["hosts:enroll"], &db.conn)
|
||||||
|
.await
|
||||||
|
.unwrap_or(TokenInfo::NotPresent);
|
||||||
|
|
||||||
|
// If neither are present, throw an error
|
||||||
|
if matches!(session_info, TokenInfo::NotPresent)
|
||||||
|
&& matches!(api_token_info, TokenInfo::NotPresent)
|
||||||
|
{
|
||||||
|
return HttpResponse::Unauthorized().json(APIErrorsResponse {
|
||||||
|
errors: vec![
|
||||||
|
APIError {
|
||||||
|
code: "ERR_UNAUTHORIZED".to_string(),
|
||||||
|
message: "This endpoint requires either a fully authenticated user or a token with the hosts:enroll scope".to_string(),
|
||||||
|
path: None,
|
||||||
|
}
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// If both are present, throw an error
|
||||||
|
if matches!(session_info, TokenInfo::AuthToken(_))
|
||||||
|
&& matches!(api_token_info, TokenInfo::ApiToken(_))
|
||||||
|
{
|
||||||
|
return HttpResponse::BadRequest().json(APIErrorsResponse {
|
||||||
|
errors: vec![
|
||||||
|
APIError {
|
||||||
|
code: "ERR_AMBIGUOUS_AUTHENTICATION".to_string(),
|
||||||
|
message: "Both a user token and an API token with the proper scope was provided. Please only provide one.".to_string(),
|
||||||
|
path: None
|
||||||
|
}
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let org_id = match api_token_info {
|
||||||
|
TokenInfo::ApiToken(tkn) => tkn.organization,
|
||||||
|
_ => {
|
||||||
|
// we have a session token, which means we have to do a db request to get the organization that this user owns
|
||||||
|
let user = match session_info {
|
||||||
|
TokenInfo::AuthToken(tkn) => tkn.session_info.user,
|
||||||
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let org = match organization::Entity::find()
|
||||||
|
.filter(organization::Column::Owner.eq(user.id))
|
||||||
|
.one(&db.conn)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
error!("database error: {}", e);
|
||||||
|
return HttpResponse::InternalServerError().json(APIErrorsResponse {
|
||||||
|
errors: vec![
|
||||||
|
APIError {
|
||||||
|
code: "ERR_DB_ERROR".to_string(),
|
||||||
|
message: "There was an error performing the database request, please try again later.".to_string(),
|
||||||
|
path: None,
|
||||||
|
}
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(org) = org {
|
||||||
|
org.id
|
||||||
|
} else {
|
||||||
|
return HttpResponse::Unauthorized().json(APIErrorsResponse {
|
||||||
|
errors: vec![
|
||||||
|
APIError {
|
||||||
|
code: "ERR_NO_ORG".to_string(),
|
||||||
|
message: "This user does not own any organizations. Try using an API token instead.".to_string(),
|
||||||
|
path: None
|
||||||
|
}
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let net_id;
|
||||||
|
|
||||||
|
let net = match network::Entity::find()
|
||||||
|
.filter(network::Column::Organization.eq(&org_id))
|
||||||
|
.one(&db.conn)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
error!("database error: {}", e);
|
||||||
|
return HttpResponse::InternalServerError().json(APIErrorsResponse {
|
||||||
|
errors: vec![
|
||||||
|
APIError {
|
||||||
|
code: "ERR_DB_ERROR".to_string(),
|
||||||
|
message: "There was an error performing the database request, please try again later.".to_string(),
|
||||||
|
path: None,
|
||||||
|
}
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(net) = net {
|
||||||
|
net_id = net.id;
|
||||||
|
} else {
|
||||||
|
return HttpResponse::Unauthorized().json(APIErrorsResponse {
|
||||||
|
errors: vec![APIError {
|
||||||
|
code: "ERR_NO_NET".to_string(),
|
||||||
|
message: "This user does not own any networks. Try using an API token instead."
|
||||||
|
.to_string(),
|
||||||
|
path: None,
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let host = match host::Entity::find()
|
||||||
|
.filter(host::Column::Id.eq(id.into_inner()))
|
||||||
|
.one(&db.conn)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(h) => h,
|
||||||
|
Err(e) => {
|
||||||
|
error!("Database error: {}", e);
|
||||||
|
return HttpResponse::InternalServerError().json(APIErrorsResponse {
|
||||||
|
errors: vec![APIError {
|
||||||
|
code: "ERR_DB_ERROR".to_string(),
|
||||||
|
message: "There was an error with the database query. Please try again later."
|
||||||
|
.to_string(),
|
||||||
|
path: None,
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let host = match host {
|
||||||
|
Some(h) => h,
|
||||||
|
None => {
|
||||||
|
return HttpResponse::Unauthorized().json(APIErrorsResponse {
|
||||||
|
errors: vec![APIError {
|
||||||
|
code: "ERR_UNAUTHORIZED".to_string(),
|
||||||
|
message:
|
||||||
|
"This resource does not exist or you do not have permission to access it."
|
||||||
|
.to_string(),
|
||||||
|
path: None,
|
||||||
|
}],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if host.network != net_id {
|
||||||
|
return HttpResponse::Unauthorized().json(APIErrorsResponse {
|
||||||
|
errors: vec![APIError {
|
||||||
|
code: "ERR_UNAUTHORIZED".to_string(),
|
||||||
|
message: "This resource does not exist or you do not have permission to access it."
|
||||||
|
.to_string(),
|
||||||
|
path: None,
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let enrollment_code = trifid_api_entities::entity::host_enrollment_code::Model {
|
||||||
|
id: random_token("ec"),
|
||||||
|
host: host.id,
|
||||||
|
expires_on: expires_in_seconds(CONFIG.tokens.enrollment_tokens_expiry_time) as i64,
|
||||||
|
};
|
||||||
|
let ec_am = enrollment_code.into_active_model();
|
||||||
|
|
||||||
|
let code = match ec_am.insert(&db.conn).await {
|
||||||
|
Ok(h) => h,
|
||||||
|
Err(e) => {
|
||||||
|
error!("Database error: {}", e);
|
||||||
|
return HttpResponse::InternalServerError().json(APIErrorsResponse {
|
||||||
|
errors: vec![APIError {
|
||||||
|
code: "ERR_DB_ERROR".to_string(),
|
||||||
|
message: "There was an error with the database query. Please try again later."
|
||||||
|
.to_string(),
|
||||||
|
path: None,
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
HttpResponse::Ok().json(EnrollmentCodeResponse {
|
||||||
|
data: EnrollmentCodeResponseData { enrollment_code: CodeResponse { code: code.id, lifetime_seconds: CONFIG.tokens.enrollment_tokens_expiry_time } },
|
||||||
|
metadata: EnrollmentCodeResponseMetadata {},
|
||||||
|
})
|
||||||
|
}
|
|
@ -27,6 +27,8 @@ pub struct Model {
|
||||||
pub enum Relation {
|
pub enum Relation {
|
||||||
#[sea_orm(has_many = "super::host_config_override::Entity")]
|
#[sea_orm(has_many = "super::host_config_override::Entity")]
|
||||||
HostConfigOverride,
|
HostConfigOverride,
|
||||||
|
#[sea_orm(has_many = "super::host_enrollment_code::Entity")]
|
||||||
|
HostEnrollmentCode,
|
||||||
#[sea_orm(has_many = "super::host_static_address::Entity")]
|
#[sea_orm(has_many = "super::host_static_address::Entity")]
|
||||||
HostStaticAddress,
|
HostStaticAddress,
|
||||||
#[sea_orm(
|
#[sea_orm(
|
||||||
|
@ -53,6 +55,12 @@ impl Related<super::host_config_override::Entity> for Entity {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Related<super::host_enrollment_code::Entity> for Entity {
|
||||||
|
fn to() -> RelationDef {
|
||||||
|
Relation::HostEnrollmentCode.def()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Related<super::host_static_address::Entity> for Entity {
|
impl Related<super::host_static_address::Entity> for Entity {
|
||||||
fn to() -> RelationDef {
|
fn to() -> RelationDef {
|
||||||
Relation::HostStaticAddress.def()
|
Relation::HostStaticAddress.def()
|
||||||
|
|
|
@ -0,0 +1,32 @@
|
||||||
|
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.2
|
||||||
|
|
||||||
|
use sea_orm::entity::prelude::*;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
|
||||||
|
#[sea_orm(table_name = "host_enrollment_code")]
|
||||||
|
pub struct Model {
|
||||||
|
#[sea_orm(primary_key, auto_increment = false)]
|
||||||
|
pub id: String,
|
||||||
|
pub host: String,
|
||||||
|
pub expires_on: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||||
|
pub enum Relation {
|
||||||
|
#[sea_orm(
|
||||||
|
belongs_to = "super::host::Entity",
|
||||||
|
from = "Column::Host",
|
||||||
|
to = "super::host::Column::Id",
|
||||||
|
on_update = "Cascade",
|
||||||
|
on_delete = "Cascade"
|
||||||
|
)]
|
||||||
|
Host,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Related<super::host::Entity> for Entity {
|
||||||
|
fn to() -> RelationDef {
|
||||||
|
Relation::Host.def()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActiveModelBehavior for ActiveModel {}
|
|
@ -8,6 +8,7 @@ pub mod auth_token;
|
||||||
pub mod firewall_rule;
|
pub mod firewall_rule;
|
||||||
pub mod host;
|
pub mod host;
|
||||||
pub mod host_config_override;
|
pub mod host_config_override;
|
||||||
|
pub mod host_enrollment_code;
|
||||||
pub mod host_static_address;
|
pub mod host_static_address;
|
||||||
pub mod magic_link;
|
pub mod magic_link;
|
||||||
pub mod network;
|
pub mod network;
|
||||||
|
|
|
@ -6,6 +6,7 @@ pub use super::auth_token::Entity as AuthToken;
|
||||||
pub use super::firewall_rule::Entity as FirewallRule;
|
pub use super::firewall_rule::Entity as FirewallRule;
|
||||||
pub use super::host::Entity as Host;
|
pub use super::host::Entity as Host;
|
||||||
pub use super::host_config_override::Entity as HostConfigOverride;
|
pub use super::host_config_override::Entity as HostConfigOverride;
|
||||||
|
pub use super::host_enrollment_code::Entity as HostEnrollmentCode;
|
||||||
pub use super::host_static_address::Entity as HostStaticAddress;
|
pub use super::host_static_address::Entity as HostStaticAddress;
|
||||||
pub use super::magic_link::Entity as MagicLink;
|
pub use super::magic_link::Entity as MagicLink;
|
||||||
pub use super::network::Entity as Network;
|
pub use super::network::Entity as Network;
|
||||||
|
|
|
@ -17,6 +17,7 @@ mod m20230404_133813_create_table_firewall_rules;
|
||||||
mod m20230427_170037_create_table_hosts;
|
mod m20230427_170037_create_table_hosts;
|
||||||
mod m20230427_171517_create_table_hosts_static_addresses;
|
mod m20230427_171517_create_table_hosts_static_addresses;
|
||||||
mod m20230427_171529_create_table_hosts_config_overrides;
|
mod m20230427_171529_create_table_hosts_config_overrides;
|
||||||
|
mod m20230511_120511_create_table_host_enrollment_codes;
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl MigratorTrait for Migrator {
|
impl MigratorTrait for Migrator {
|
||||||
|
@ -37,6 +38,7 @@ impl MigratorTrait for Migrator {
|
||||||
Box::new(m20230427_170037_create_table_hosts::Migration),
|
Box::new(m20230427_170037_create_table_hosts::Migration),
|
||||||
Box::new(m20230427_171517_create_table_hosts_static_addresses::Migration),
|
Box::new(m20230427_171517_create_table_hosts_static_addresses::Migration),
|
||||||
Box::new(m20230427_171529_create_table_hosts_config_overrides::Migration),
|
Box::new(m20230427_171529_create_table_hosts_config_overrides::Migration),
|
||||||
|
Box::new(m20230511_120511_create_table_host_enrollment_codes::Migration),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,43 @@
|
||||||
|
use sea_orm_migration::prelude::*;
|
||||||
|
use crate::m20230427_170037_create_table_hosts::Host;
|
||||||
|
|
||||||
|
#[derive(DeriveMigrationName)]
|
||||||
|
pub struct Migration;
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl MigrationTrait for Migration {
|
||||||
|
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||||
|
manager
|
||||||
|
.create_table(
|
||||||
|
Table::create()
|
||||||
|
.table(HostEnrollmentCode::Table)
|
||||||
|
.col(ColumnDef::new(HostEnrollmentCode::Id).string().not_null().primary_key())
|
||||||
|
.col(ColumnDef::new(HostEnrollmentCode::Host).string().not_null())
|
||||||
|
.col(ColumnDef::new(HostEnrollmentCode::ExpiresOn).big_integer().not_null())
|
||||||
|
.foreign_key(
|
||||||
|
ForeignKey::create()
|
||||||
|
.from(HostEnrollmentCode::Table, HostEnrollmentCode::Host)
|
||||||
|
.to(Host::Table, Host::Id)
|
||||||
|
.on_update(ForeignKeyAction::Cascade)
|
||||||
|
.on_delete(ForeignKeyAction::Cascade)
|
||||||
|
)
|
||||||
|
.to_owned(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||||
|
manager
|
||||||
|
.drop_table(Table::drop().table(HostEnrollmentCode::Table).to_owned())
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Learn more at https://docs.rs/sea-query#iden
|
||||||
|
#[derive(Iden)]
|
||||||
|
pub enum HostEnrollmentCode {
|
||||||
|
Table,
|
||||||
|
Id,
|
||||||
|
Host,
|
||||||
|
ExpiresOn
|
||||||
|
}
|
Loading…
Reference in New Issue