Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
023905e
feat(identity-resolution): port roles catalogue endpoints (#1755)
mozhaev-dev Jul 22, 2026
70f3208
feat(identity-resolution): port person-roles endpoints (#1755)
mozhaev-dev Jul 22, 2026
f0daf81
feat(identity-resolution): port visibility endpoints (#1755)
mozhaev-dev Jul 22, 2026
edb1dd5
Merge branch 'feat/identity-resolution-write-seed' into feat/identity…
mozhaev-dev Jul 22, 2026
49808dc
Merge branch 'feat/identity-resolution-write-seed' into feat/identity…
mozhaev-dev Jul 22, 2026
c8b36fe
fix(identity-resolution): drop next_cursor from roles/person-roles/vi…
mozhaev-dev Jul 22, 2026
f26c9c7
Merge branch 'feat/identity-resolution-write-seed' into feat/identity…
mozhaev-dev Jul 22, 2026
a69271c
docs(identity-resolution): mark roles/person-roles atomic-DML raw-SQL…
mozhaev-dev Jul 22, 2026
02feb6a
Merge branch 'feat/identity-resolution-write-seed' into feat/identity…
mozhaev-dev Jul 22, 2026
44e9dcf
Merge branch 'feat/identity-resolution-write-seed' into feat/identity…
mozhaev-dev Jul 22, 2026
4f33777
Merge branch 'feat/identity-resolution-write-seed' into feat/identity…
mozhaev-dev Jul 22, 2026
afd36a3
feat(identity-resolution): port internal service-only by-email lookup…
mozhaev-dev Jul 22, 2026
17a685b
feat(identity-resolution): port org subchart (single + forest) (#1755)
mozhaev-dev Jul 22, 2026
214e215
fix(identity-resolution): address full-branch review (#1755)
mozhaev-dev Jul 22, 2026
1c2c788
fix(identity-resolution): bound subchart depth + surface dropped org …
mozhaev-dev Jul 23, 2026
071325c
Merge remote-tracking branch 'upstream/main' into feat/identity-resol…
mozhaev-dev Jul 23, 2026
04b8bb3
fix(identity-resolution): address CodeRabbit review on #1862 (#1755)
mozhaev-dev Jul 23, 2026
71eed53
fix(identity-resolution): restore visibility gate on POST /v1/profile…
mozhaev-dev Jul 23, 2026
04c9dfa
fix(identity-resolution): RFC3339 valid_from + concurrent-duplicate r…
mozhaev-dev Jul 23, 2026
a3a82dc
fix(identity-resolution): link OIDC plugin + de-stale docs/allows (#1…
mozhaev-dev Jul 23, 2026
d6c53d8
fix(identity-resolution): filter visibility before ambiguity + dedupe…
mozhaev-dev Jul 24, 2026
7400878
Merge remote-tracking branch 'upstream/main' into feat/identity-resol…
mozhaev-dev Jul 24, 2026
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
17 changes: 10 additions & 7 deletions src/backend/services/identity-resolution/README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
# identity-resolution

Rust port of the .NET `identity` service (epic #1602). **Iteration 1: read API.**
Rust port of the .NET `identity` service (epic #1602).
Built on the gears-rust framework — same host pattern as `services/analytics`
(the `api-gateway` system gear is the REST host; auth disabled — the platform
gateway authenticates upstream).

Current state: boots as a gears host, connects to MariaDB on startup, serves
`/health`, and implements the read API — `POST /v1/profiles` (attributes, `ids[]`,
org tree) plus the deprecated `GET /v1/persons/{email}`.
(the `api-gateway` system gear is the REST host; auth ENABLED — the
`oidc-authn-plugin` verifies the gateway JWT and maps its claims into the
`SecurityContext`).

Current state: boots as a gears host, connects to MariaDB on startup, and
implements the full ported surface — `POST /v1/profiles` (attributes, `ids[]`,
org tree), persons-seed, roles / person-roles / visibility, org subchart, and
the internal service-only `GET /internal/persons/by-email/{email}`. (The
deprecated .NET `GET /v1/persons/{email}` is intentionally not carried.)

## Run locally against the dev cluster DB

Expand Down
126 changes: 126 additions & 0 deletions src/backend/services/identity-resolution/src/api/datetime.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
//! Flexible date-time parsing for request DTOs.
//!
//! The .NET API accepts OpenAPI `format: date-time` (RFC-3339 with `Z` or a
//! numeric offset). `sea_orm::prelude::DateTime` is `chrono::NaiveDateTime`,
//! whose serde parser rejects `Z`/offset forms, so a normal client value like
//! `2026-07-23T10:00:00Z` would 400 before the handler. These helpers accept the
//! same forms the .NET binder does — RFC-3339 with `Z`/offset, a zone-less
//! datetime (treated as UTC), or a date-only value (midnight UTC) — and
//! normalise everything to naive-UTC (the DB column type).

use chrono::{DateTime as ChronoDateTime, NaiveDate, NaiveDateTime, Utc};
use serde::{Deserialize, Deserializer};

/// Parse the accepted date-time forms to naive-UTC. Returns `None` if the string
/// matches none of them.
#[must_use]
pub(crate) fn parse_flexible(raw: &str) -> Option<NaiveDateTime> {
if let Ok(dt) = ChronoDateTime::parse_from_rfc3339(raw) {
return Some(dt.with_timezone(&Utc).naive_utc());
}
if let Ok(ndt) = NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M:%S%.f") {
return Some(ndt);
}
if let Ok(ndt) = NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M:%S") {
return Some(ndt);
}
NaiveDate::parse_from_str(raw, "%Y-%m-%d")
.ok()
.and_then(|d| d.and_hms_opt(0, 0, 0))
}

/// serde `deserialize_with` for an optional timestamp: accepts the RFC-3339 /
/// zone-less / date-only forms and normalises to naive-UTC. Absent / empty →
/// `None`; an unrecognised string is a deserialization error (surfaces as 400).
///
/// # Errors
///
/// Returns a deserialization error if the value is present but not a recognised
/// date-time.
pub(crate) fn deserialize_opt<'de, D>(deserializer: D) -> Result<Option<NaiveDateTime>, D::Error>
where
D: Deserializer<'de>,
{
let raw = Option::<String>::deserialize(deserializer)?;
match raw {
None => Ok(None),
Some(s) if s.trim().is_empty() => Ok(None),
Some(s) => parse_flexible(s.trim())
.map(Some)
.ok_or_else(|| serde::de::Error::custom(format!("invalid date-time: '{s}'"))),
}
}

#[cfg(test)]
mod tests {
use super::*;

fn ymd_hms(y: i32, mo: u32, d: u32, h: u32, mi: u32, s: u32) -> anyhow::Result<NaiveDateTime> {
use anyhow::Context;
NaiveDate::from_ymd_opt(y, mo, d)
.and_then(|date| date.and_hms_opt(h, mi, s))
.context("valid datetime")
}

#[test]
fn accepts_rfc3339_and_zoneless_and_date_only() -> anyhow::Result<()> {
let utc10 = ymd_hms(2026, 7, 23, 10, 0, 0)?;
assert_eq!(parse_flexible("2026-07-23T10:00:00Z"), Some(utc10), "Z");
assert_eq!(
parse_flexible("2026-07-23T10:00:00"),
Some(utc10),
"zone-less"
);
// +03:00 → 07:00 UTC
assert_eq!(
parse_flexible("2026-07-23T10:00:00+03:00"),
Some(ymd_hms(2026, 7, 23, 7, 0, 0)?),
"offset"
);
assert_eq!(
parse_flexible("2026-07-23"),
Some(ymd_hms(2026, 7, 23, 0, 0, 0)?),
"date-only"
);
assert_eq!(parse_flexible("not-a-date"), None);
Ok(())
}

#[derive(Deserialize)]
struct OptWrapper {
#[serde(default, deserialize_with = "deserialize_opt")]
at: Option<NaiveDateTime>,
}

#[test]
fn deserialize_opt_boundary_cases() -> anyhow::Result<()> {
let missing: OptWrapper = serde_json::from_value(serde_json::json!({}))?;
assert_eq!(missing.at, None, "missing field");

let null: OptWrapper = serde_json::from_value(serde_json::json!({ "at": null }))?;
assert_eq!(null.at, None, "null");

let empty: OptWrapper = serde_json::from_value(serde_json::json!({ "at": "" }))?;
assert_eq!(empty.at, None, "empty string");

let blank: OptWrapper = serde_json::from_value(serde_json::json!({ "at": " " }))?;
assert_eq!(blank.at, None, "blank string");

let valid: OptWrapper = serde_json::from_value(serde_json::json!({
"at": "2026-07-23T10:00:00Z"
}))?;
assert_eq!(
valid.at,
Some(ymd_hms(2026, 7, 23, 10, 0, 0)?),
"valid RFC-3339"
);

let invalid: Result<OptWrapper, _> =
serde_json::from_value(serde_json::json!({ "at": "not-a-date" }));
assert!(
invalid.is_err(),
"invalid string is a deserialization error"
);
Ok(())
}
}
17 changes: 17 additions & 0 deletions src/backend/services/identity-resolution/src/api/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,20 @@ pub struct ProfileError;

#[resource_error("gts.cf.insight.identity_resolution.persons_seed.v1~")]
pub struct PersonsSeedError;

/// Shared admin-gate errors (401 no caller / 403 not admin), used by every
/// admin-gated endpoint via [`crate::api::gate`].
#[resource_error("gts.cf.insight.identity_resolution.access.v1~")]
pub struct AccessError;

#[resource_error("gts.cf.insight.identity_resolution.role.v1~")]
pub struct RoleError;

#[resource_error("gts.cf.insight.identity_resolution.person_role.v1~")]
pub struct PersonRoleError;

#[resource_error("gts.cf.insight.identity_resolution.visibility.v1~")]
pub struct VisibilityError;

#[resource_error("gts.cf.insight.identity_resolution.subchart.v1~")]
pub struct SubchartError;
113 changes: 113 additions & 0 deletions src/backend/services/identity-resolution/src/api/gate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
//! Shared admin gate for the mutating / admin identity-resolution endpoints.
//!
//! Ported from the .NET `CallerAdminCheck`: the caller is the gateway-JWT
//! subject (`SecurityContext::subject_id`, verified by the host authn pipeline —
//! `NGINX_BFF` R1), which must hold an active `admin` role in the tenant. Reused
//! by the persons-seed, roles, person-roles, and visibility endpoints.

use sea_orm::DatabaseConnection;
use toolkit_canonical_errors::CanonicalError;
use toolkit_security::SecurityContext;
use uuid::Uuid;

use crate::api::error::AccessError;
use crate::infra::db::roles_repo;

/// Require an identified caller (gateway-JWT subject). Returns the caller
/// `person_id`, or 401 when the JWT carries no person subject. The baseline gate
Comment thread
cyberantonz marked this conversation as resolved.
Resolved
/// for authenticated-but-not-admin endpoints (e.g. subchart).
///
/// # Errors
///
/// 401 if the JWT carries no person subject.
pub(crate) fn require_caller(ctx: &SecurityContext) -> Result<Uuid, CanonicalError> {
let caller = ctx.subject_id();
if caller.is_nil() {
return Err(CanonicalError::unauthenticated()
.with_reason("caller not identified: the gateway JWT carries no person subject")
.create());
}
// A nil tenant reaches here only from a misconfigured token (the gateway JWT
// should always carry a real tenant). Surface it as an explicit 400 instead
// of silently flowing a nil tenant into every query (→ empty/404), which is
// hard to diagnose. Rough parity with the .NET `tenant_unresolved` 400.
if ctx.subject_tenant_id().is_nil() {
return Err(AccessError::failed_precondition()
.with_precondition_violation(
"tenant",
"tenant not resolved from the gateway JWT",
"tenant_unresolved",
)
.create());
}
Ok(caller)
}

/// Resolve the caller (gateway-JWT subject) and require an active `admin` role
/// in the tenant. Returns the caller `person_id`, or 401 (no subject) / 403
/// (not admin).
///
/// # Errors
///
/// 401 if the JWT carries no person subject, 403 if the caller is not an admin,
/// 500 on DB error.
pub(crate) async fn require_admin(
db: &DatabaseConnection,
ctx: &SecurityContext,
) -> Result<Uuid, CanonicalError> {
let caller = require_caller(ctx)?;
let is_admin = roles_repo::has_active_admin(db, ctx.subject_tenant_id(), caller)
.await
.map_err(|e| {
tracing::error!(error = %e, "admin role check failed");
CanonicalError::internal("failed to verify caller permissions").create()
})?;
if !is_admin {
tracing::warn!(
caller = %caller,
tenant = %ctx.subject_tenant_id(),
"admin gate denied: caller has no active admin role"
);
return Err(AccessError::permission_denied()
.with_reason("admin role required for this operation")
.create());
}
Ok(caller)
}

/// Require a SERVICE principal (gateway JWT `sub_type=service`). Used by the
/// internal S2S endpoints that run before a tenant/caller identity exists (the
/// login-bootstrap by-email lookup). 403 for any non-service caller.
///
/// # Errors
///
/// 403 if the caller is not a service principal.
pub(crate) fn require_service(ctx: &SecurityContext) -> Result<(), CanonicalError> {
if ctx.subject_type() != Some("service") {
return Err(AccessError::permission_denied()
.with_reason("this endpoint is restricted to service principals (sub_type=service)")
.create());
}
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;

fn ctx(subject_type: &str) -> anyhow::Result<SecurityContext> {
SecurityContext::builder()
.subject_id(Uuid::from_u128(1))
.subject_type(subject_type)
.subject_tenant_id(Uuid::from_u128(2))
.build()
.map_err(|e| anyhow::anyhow!("build security context: {e:?}"))
}

#[test]
fn require_service_allows_only_service_principals() -> anyhow::Result<()> {
assert!(require_service(&ctx("service")?).is_ok(), "service allowed");
assert!(require_service(&ctx("user")?).is_err(), "user rejected");
Ok(())
}
}
Loading
Loading